Jan 8, 20232 min read
CRUD APIs Using FastAPI
Python

To create a CRUD (create, read, update, delete) API with FastAPI, you will need to:
- Install FastAPI:
pip install fastapi
- Define a model for the data that the API will handle. This can be a Pydantic model, which is a simple Python class with class variables and type annotations. For example:
from pydantic import BaseModelclass Item(BaseModel):
name: str
description: str
price: float
tax: float- Create a database to store the data. You can use any database system that you prefer, such as PostgreSQL or MongoDB.
- Define the API endpoints using FastAPI’s
@app.post,@app.get,@app.put, and@app.deletedecorators. For example:
from fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()
class Item(BaseModel):
name: str
description: str
price: float
tax: float@app.post("/items/")
async def create_item(item: Item):
return {"item_id": 123}@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id, "name": "Foo", "description": "A very nice Item", "price": 50.2, "tax": 3.2}@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_id": item_id, "name": item.name, "description": item.description, "price": item.price, "tax": item.tax}@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
return {"item_id": item_id}- In the functions handling the API endpoints, you will need to perform the appropriate database operations to create, read, update, or delete the data.
- Run the API using
uvicorn:
uvicorn main:app --reload
This is a basic example of how to create a CRUD API with FastAPI. There are many other features and options that you can use to customize and extend your API. You can find more information in the FastAPI documentation: https://fastapi.tiangolo.com/
Thank You for reading!
You can Also Follow Me on My Social Media Platforms: