
FastAPI
HTTP methods define what action an API endpoint should perform. The main methods are GET, POST, PUT, PATCH, and DELETE.
Fetch data without modifying anything.
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"id": user_id, "name": "John"}Usage:
Create a new resource.
@app.post("/users")
async def create_user(user: User):
new_id = db.insert(user)
return {"id": new_id, **user.dict()}Request:
{"name": "Jane", "email": "jane@example.com"}Response (201 Created):
{"id": 2, "name": "Jane", "email": "jane@example.com"}Replace an entire resource.
@app.put("/users/{user_id}")
async def update_user(user_id: int, user: User):
db.replace(user_id, user)
return {"id": user_id, **user.dict()}Must provide complete object.
Update only specific fields.
@app.patch("/users/{user_id}")
async def patch_user(user_id: int, update: UserUpdate):
db.patch(user_id, update)
return db.get(user_id)Only include fields to change.
Delete a resource.
@app.delete("/users/{user_id}")
async def delete_user(user_id: int):
db.delete(user_id)
return {"deleted": True}Response (204 No Content):
Empty response with status 204.
| Method | Purpose | Request Body | Response |
|---|---|---|---|
| GET | Retrieve | No | Data |
| POST | Create | Yes | Created object |
| PUT | Replace | Yes | Updated object |
| PATCH | Update | Yes | Updated object |
| DELETE | Remove | No | Empty (204) |
@app.get("/products")
async def list_products():
return db.list()
@app.post("/products")
async def create_product(product: Product):
return db.create(product)
@app.get("/products/{product_id}")
async def get_product(product_id: int):
return db.get(product_id)
@app.put("/products/{product_id}")
async def replace_product(product_id: int, product: Product):
return db.replace(product_id, product)
@app.delete("/products/{product_id}")
async def delete_product(product_id: int):
db.delete(product_id)
return NoneResources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward