Back to Blog
Jan 8, 20232 min read

CRUD APIs Using FastAPI

Python
CRUD APIs Using FastAPI

To create a CRUD (create, read, update, delete) API with FastAPI, you will need to:

  1. Install FastAPI:
pip install fastapi
  1. 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 BaseModel
class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float
  1. Create a database to store the data. You can use any database system that you prefer, such as PostgreSQL or MongoDB.
  2. Define the API endpoints using FastAPI’s @app.post, @app.get, @app.put, and @app.delete decorators. For example:
from fastapi import FastAPI
from pydantic import BaseModel
app = 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}
  1. In the functions handling the API endpoints, you will need to perform the appropriate database operations to create, read, update, or delete the data.
  2. 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:

  1. Facebook
  2. Youtube
  3. Twitter & Instagram
  4. GitHub & Replit
  5. Upwork:

💬 Got questions? Ask me anything!