
FastAPI
Learn the fundamentals of response codes in FastAPI.
HTTP status codes communicate the outcome of an API request. Choosing the correct status code is essential for client applications to understand what happened and how to respond appropriately.
In this section, you'll understand:
from fastapi import FastAPI, status, HTTPException
app = FastAPI()
@app.get("/items/{item_id}", status_code=status.HTTP_200_OK)
async def get_item(item_id: int):
return {"id": item_id}
@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
return {"id": 1, **item.dict()}
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int):
return None
@app.get("/items/{item_id}", status_code=status.HTTP_200_OK)
async def get_item_or_404(item_id: int):
if item_id < 1:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found"
)
return {"id": item_id}# GET (retrieve)
@app.get("/users/{user_id}", status_code=200) # OK
# POST (create)
@app.post("/users", status_code=201) # Created
# PUT (replace)
@app.put("/users/{user_id}", status_code=200) # OK
# PATCH (partial update)
@app.patch("/users/{user_id}", status_code=200) # OK
# DELETE
@app.delete("/users/{user_id}", status_code=204) # No Contentfrom fastapi.responses import JSONResponse
@app.post("/items")
async def create_or_update(item: Item, db: Session = Depends(get_db)):
existing = db.query(Item).filter_by(id=item.id).first()
if existing:
existing.update(**item.dict())
return JSONResponse(
status_code=200,
content={"status": "updated"}
)
else:
db.add(Item(**item.dict()))
return JSONResponse(
status_code=201,
content={"status": "created"}
)Ready to explore more? Check out the advanced section for production patterns and edge cases.
Resources
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