0
0
FastAPIframework~5 mins

CRUD operations in FastAPI

Choose your learning style9 modes available
Introduction

CRUD operations let you create, read, update, and delete data in your app. They help manage information easily.

Building a web app that stores user profiles.
Making a blog where you add, edit, or remove posts.
Creating a task manager to track tasks and update their status.
Developing an inventory system to add or remove products.
Setting up a contact list where you can save and change contacts.
Syntax
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    id: int
    name: str
    description: str | None = None

items = {}

@app.post("/items/")
async def create_item(item: Item):
    items[item.id] = item
    return item

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return items.get(item_id)

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    items[item_id] = item
    return item

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    return items.pop(item_id, None)

Use @app.post to create new data.

Use @app.get to read or get data.

Use @app.put to update existing data.

Use @app.delete to remove data.

Examples
Create a new user and save it in the users dictionary.
FastAPI
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str

users = {}

@app.post("/users/")
async def create_user(user: User):
    users[user.id] = user
    return user
Get user details by user ID.
FastAPI
@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return users.get(user_id)
Update user information by user ID.
FastAPI
@app.put("/users/{user_id}")
async def update_user(user_id: int, user: User):
    users[user_id] = user
    return user
Delete a user by user ID.
FastAPI
@app.delete("/users/{user_id}")
async def delete_user(user_id: int):
    return users.pop(user_id, None)
Sample Program

This FastAPI app lets you add, get, update, and delete items using simple web requests. It stores items in a dictionary for easy access.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    id: int
    name: str
    description: str | None = None

items = {}

@app.post("/items/")
async def create_item(item: Item):
    items[item.id] = item
    return {"message": "Item created", "item": item}

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    item = items.get(item_id)
    if item:
        return item
    return {"error": "Item not found"}

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    if item_id in items:
        items[item_id] = item
        return {"message": "Item updated", "item": item}
    return {"error": "Item not found"}

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    if item_id in items:
        removed = items.pop(item_id)
        return {"message": "Item deleted", "item": removed}
    return {"error": "Item not found"}
OutputSuccess
Important Notes

FastAPI uses Python type hints to check data automatically.

Use Pydantic models to define the shape of your data clearly.

Data is stored in memory here; for real apps, use a database.

Summary

CRUD means Create, Read, Update, Delete data.

FastAPI makes it easy to build these operations with simple decorators.

Use Pydantic models to define and validate your data.