![](https://crypto4nerd.com/wp-content/uploads/2023/07/0Swqi8QJc24pqod1r.jpeg)
FastAPI: The Swift Solution for Lightning-Fast Python APIs
Hola! Welcome to the exciting world of FastAPI — the high-performance web framework for building APIs with Python. In this blog post, we’re going to dive into the fascinating features and benefits of FastAPI that make it a game-changer in the realm of backend development.
The only pre-requisite for this series is: Python
In todays Blog we will discuss on the following points:
- What is FastAPI?
- Advantages of FastAPI over traditional API frameworks
- How to install FastAPI?
- Create BackEnd API using FastAPI frame-work
- Swagger documentation
FastAPI is a modern web framework for building APIs for Python. It is designed to be fast, efficient, and developer-friendly, offering a delightful development experience. It helps us with python type hints for automatic data validation and generates interactive API documentation. With its focus on speed, simplicity, and modern Python features, FastAPI is popular for building robust and scalable APIs.
- Performance: FastAPI is developed on top of the Starlette framework and makes use of Python’s asyncio package for asynchronous programming. This enables it to effectively manage heavy loads and several concurrent requests, leading to exceptional performance and scalability.
- Type Hints and Validation: It helps us with python type hints for automatic request/response data validation, reducing chances of errors.
- Automatic Documentation: FastAPI generates interactive API documentation automatically based on your code’s type hints. This eliminates the need for separate documentation efforts and provides a user-friendly interface for exploring and testing API endpoints.
- Modern Syntax: FastAPI makes use of modern Python syntax, including type hints and data classes. As a result, the codebase is easier to read, maintain, and is less prone to errors.
- Dependency Injection: With the advantage of dependency injection, we now have code modularity and testability, making your codebase more robust.
- Security: It can also provide built-in support for authentication and authorization mechanism, which implement secure authentication for our API endpoints.
- Extensibility: FastAPI also provides extensibility, so now we have flexibility to choose the components that best fit our project requirements.
- Async Support: FastAPI is helps in managing I/O-bound processes like communicating with databases or making API calls to other services because it fully supports asynchronous programming. Our API’s performance and responsiveness can be enhanced through asynchronous programming.
In short we can say that, it is a high performance web framework even faster then Node.js, it is also easy to develop and we can easily make Swagger UI to form API Documentation, along with that it avoids redundancy of code and it is easy to test.
For that you need to have pip/pip3 installed in your system, if you don’t have kindly follow this article to install.
Install FastAPI using pip/pip3
pip install fastapi
Install the uvicorn which is the Asynchronous Gateway Interface for your Server
pip install uvicorn
But, before that we need to setup FastAPI in our python script.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
Lets make a basic CRUD API using FastAPI excited 😮
CRUD stands for create, read, update and delete.
We are going to use MongoDB. If you don’t know how to setup mongoDB then go through this article.
So, now I assume you have successfully setup your account there and create a cluster. Make the database there giving name ‘Projects’ and give the name of the collection ‘FastAPIDB’.
Lets first connect to mongoDB
You need to first install pymongo
pip install pymongo
import pymongo
path = "mongodb+srv://modabbir7032:<password>@bepeepcode.onwwoq5.mongodb.net/?retryWrites=true&w=majority"
client = pymongo.MongoClient(path)
db=client["Projects"]
collection = db["FastAPIDB"]
Setting up the model for the item
class Item(BaseModel):
id: int
name: str
price: float
Create
@app.post("/items/")
def create_item(item: Item):
item_data = item.dict()
result = collection.insert_one(item_data)
return item
Read
# Get all items
@app.get("/items/")
def get_items():
items = collection.find()
return list(items)
# Get any specific item
@app.get("/items/{item_id}")
def get_item(item_id: str):
item = collection.find_one({"id": item_id})
if item:
return item
return {"error": "Item not found"}
Update
@app.put("/items/{item_id}")
def update_item(item_id: str, item: Item):
updated_item = item.dict()
result = collection.update_one({"id": item_id}, {"$set": updated_item})
if result.modified_count > 0:
return {"message": "Item updated successfully"}
return {"error": "Item not found"}
Delete
@app.delete("/items/{item_id}")
def delete_item(item_id: str):
result = collection.delete_one({"id": item_id})
if result.deleted_count > 0:
return {"message": "Item deleted successfully"}
return {"error": "Item not found"}
Note:
1. Here we had imported pymongo for creating a connection between python and mobgoDB
2. Replace <password> with your mongoDB password that you have set.
Congratulations!!! we did it 😄.
Now to start the server run this command:
uvicorn main:app --reload
Now, you can play with your API on Postman 😁
Now, you can access the Swagger UI by navigating to http://localhost:8000/docs
in your web browser. It will provide an interactive documentation interface where you can explore the API endpoints, view request and response examples, and even test the API directly.
In conclusion, this article has explored the process of creating a CRUD API using FastAPI, a powerful Python framework for building web APIs. We began by understanding the basics of FastAPI and its key features, such as automatic documentation generation and type validation using Pydantic models along with that its advantages over traditional FrameWorks. Next, we explored the implementation of a CRUD API, which involved diving deep into the core operations of creating, reading, updating, and deleting data. By understanding each of these essential operations, we gained insight into how to interact with our API and manipulate data effectively. Happy coding!
If you are interested you can check my code here: GitHub.
Feel free to connect me on LinkedIn
Thanks for reading!