0
0
FastAPIframework~5 mins

Path operations (GET, POST, PUT, DELETE) in FastAPI

Choose your learning style9 modes available
Introduction

Path operations let your web app respond to different requests like getting data, sending new data, updating, or deleting it. They make your app interactive and useful.

When you want to show information to users (GET).
When users submit new data, like a form (POST).
When you need to change existing data (PUT).
When you want to remove data (DELETE).
Syntax
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/path")
async def read_item():
    return {"message": "GET request"}

@app.post("/path")
async def create_item():
    return {"message": "POST request"}

@app.put("/path")
async def update_item():
    return {"message": "PUT request"}

@app.delete("/path")
async def delete_item():
    return {"message": "DELETE request"}

Each decorator (@app.get, @app.post, etc.) tells FastAPI which HTTP method to listen for.

Functions below decorators handle the request and return a response.

Examples
This GET path takes an item ID from the URL and returns it.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
This POST path accepts JSON data to create a new item.
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    return {"item_name": item.name, "item_price": item.price}
This PUT path updates an item by its ID.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.put("/items/{item_id}")
async def update_item(item_id: int):
    return {"message": f"Item {item_id} updated"}
This DELETE path removes an item by its ID.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    return {"message": f"Item {item_id} deleted"}
Sample Program

This example shows a simple in-memory store for items. You can create, read, update, and delete items by their ID using the correct HTTP method.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

items_db = {}

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

@app.post("/items/{item_id}")
async def create_item(item_id: int, item: Item):
    if item_id in items_db:
        return {"error": "Item already exists"}
    items_db[item_id] = item.dict()
    return {"message": "Item created", "item": items_db[item_id]}

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

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    if item_id in items_db:
        del items_db[item_id]
        return {"message": "Item deleted"}
    return {"error": "Item not found"}
OutputSuccess
Important Notes

Use the correct HTTP method to match the action you want (GET to read, POST to create, etc.).

Path parameters like {item_id} let you work with specific items easily.

FastAPI automatically converts and validates data types for you.

Summary

Path operations define how your app responds to different HTTP requests.

GET reads data, POST creates, PUT updates, DELETE removes.

Use path parameters to work with specific resources.