Status Codes

Choosing Status Codes

CodeMeaningTypical use
200 OKsuccessGET, PUT
201 Createdresource createdPOST
204 No Contentsuccess, empty bodyDELETE
400 Bad Requestinvalid requestbusiness rule violated
401 / 403not authenticated / not allowedauth
404 Not Foundresource does not existGET by id
409 Conflictstate conflictduplicate email
422 Unprocessable Entityvalidation failedsent automatically by FastAPI

Setting the Status Code

Example

from fastapi import FastAPI, Response, status

app = FastAPI()
TAGS = {"python", "api"}

@app.post("/tags/{name}", status_code=status.HTTP_201_CREATED)
def add_tag(name: str):
    TAGS.add(name)
    return {"created": name}

@app.delete("/tags/{name}", status_code=status.HTTP_204_NO_CONTENT)
def delete_tag(name: str):
    TAGS.discard(name)
    return Response(status_code=status.HTTP_204_NO_CONTENT)

Requests and responses

POST /tags/docker
→ 201 {"created": "docker"}
DELETE /tags/docker
→ 204