Show a simple example of a fastapi route that returns a simple value, or responds with an error. Be sure to use best practices…

john:

Show a simple example of a fastapi route that returns a simple value, or responds with an error. Be sure to use best practices with the response. I want to learn how to return a response correctly from a route.

Chatbot:

Of course! When writing FastAPI routes, the most robust way to return responses is to:

  • Use type hints for return values.
  • Return Pydantic models or dicts for successful responses.
  • Raise HTTPException for error responses (so FastAPI properly sets the HTTP status code and error details).

Let’s see a minimal, well-structured example that demonstrates both a successful return and an error return:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()


class ItemResponse(BaseModel):
    message: str
    value: int


@app.get("/item/{item_id}", response_model=ItemResponse)
async def get_item(item_id: int):
    # Example: Only allow item_id == 1 for demo purposes
    if item_id != 1:
        # Responds with 404 and a JSON error
        raise HTTPException(status_code=404, detail="Item not found!")

    # Successful response using the Pydantic model
    return ItemResponse(message="Here is your item!", value=item_id)

Key Points:

  • Best Practice: Use response_model in your route decorator so FastAPI validates and documents your output.
  • Recommended: Return a Pydantic model instance for successful data.
  • For errors: Use raise HTTPException(...) with the desired status code and detail message.
  • Automatic: FastAPI handles converting your object to JSON and the correct HTTP status code.

Testing:

  • /item/1 returns:

    {
      "message": "Here is your item!",
      "value": 1
    }
    
  • /item/2 returns:

    {
      "detail": "Item not found!"
    }
    

    (with status code 404)

Let me know if you want more about custom error handling, custom responses, or additional FastAPI tips!

john:

Show me a list of commonly used status codes.

Chatbot:

Absolutely! Here’s a practical list of HTTP status codes commonly used in FastAPI (and most APIs), along with their typical purpose:


Common HTTP Status Codes

Code Name Use Case
200 OK Successful GET or general success
201 Created Resource created successfully (e.g., POST)
204 No Content Successful, but no body to return (e.g., DELETE)
400 Bad Request Client sent invalid data
401 Unauthorized Authentication required or failed
403 Forbidden Authenticated but not permitted
404 Not Found Resource not found
409 Conflict Resource conflict (e.g., duplicate)
422 Unprocessable Entity Validation error with well-formed data (common in FastAPI)
500 Internal Server Error Unexpected server error

How to use in FastAPI

For manual error responses, use:

from fastapi import HTTPException

raise HTTPException(status_code=404, detail="Not found")

Or set the status code for success responses:

from fastapi import status

@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(...):
    ...

Tip:
FastAPI includes these status codes in fastapi.status for convenience:

from fastapi import status

status.HTTP_200_OK
status.HTTP_201_CREATED
status.HTTP_400_BAD_REQUEST
# etc.

Let me know if you want a full list or examples of custom error handling!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *