python-3.xfastapi

How to list additional possible error HTTP codes for endpoint?


I am using the fastAPI to build API.

It allows to generate API docs automatically. enter image description here

It also shows list of possible response codes. By default it shows only a success code and 422 code.

But in my app there are more codes allowed. For example 404, 401, 403 etc. All these exceptions are not inside a code of en endpoint. It is inside a package

@app.get("/items/{item_id}")
async def read_item(item_id: str):
    data, error, message = do_something()
    if error != 0:
        raise HTTPException(status_code=error, detail=message)
    return data

How can i notify the decorator about all possible codes? is it possible?


Solution

  • You can use APIRouter in fastapi to define routes and customized responses:

    from fastapi import HTTPException, APIRouter
    
    router = APIRouter()
    
    @router.get("/items/{item_id}")
    async def read_item(item_id: str):
        data, error, message = do_something()
        if error != 0:
            raise HTTPException(status_code=error, detail=message)
        return data
    

    then you can define your desired responses:

    read_item.responses = {
        200: {"description": "Successful response"},
        404: {"description": "Item not found"},
        401: {"description": "Unauthorized access"},
        403: {"description": "Forbidden access"}
    }
    

    Another approach is to define response in @router.get():

    @router.get("/items/{item_id}",
        description="Retrieves an item by its ID.",
        response_model=Item,
        responses={
            200: {"description": "Successful response"},
            404: {"description": "Item not found"},
            401: {"description": "Unauthorized access"},
            403: {"description": "Forbidden access"}
        }
    )