How to Group API Endpoints in FastAPI: Diverse Approaches

Introduction

Today, this article is to explore how can we group the api end points using FastAPI. In FastAPI, grouping API endpoints allows you to organize and manage your routes more efficiently. You can group related endpoints together, making your codebase cleaner and easier to maintain. In this article, we'll explore two different approaches to achieve this goal of organizing and grouping API endpoints for improved maintainability and readability.

First Approach. Using APIRouter for Grouping Endpoints

In the first approach, we utilize FastAPI's APIRouter to group related endpoints. We create separate routers for users and items, encapsulating their respective endpoints. This approach provides a clear separation of concerns and facilitates better organization of code.

Implementation

We create two instances of APIRouter, namely router_user, and router_item, to handle user-related and item-related endpoints, respectively. Each router contains endpoint functions prefixed with /users and /items, signifying their respective groups. For example, /users endpoints handle user-related operations, while /items endpoints handle item-related operations. These routers are then included in the main FastAPI application using the app.include_router(), along with specifying prefixes and tags for each group.

Here’s an example of how you can use APIRouter to group your API endpoints.

from fastapi import FastAPI, APIRouter

app = FastAPI()
router_item = APIRouter()
router_user =APIRouter()

@router_user.get("/users/")
async def get_users():
    return [{"name": "Harry"}, {"name": "Ron"}]

@router_user.get("/users1/")
async def get_other_users():
    return [{"name": "Priya"}, {"name": "Riya"}]


@router_item.get("/items/")
async def get_items():
    return [{"name": "wand"}, {"name": "flying broom"}]

@router_item.get("/items1/")
async def get_other_items():
    return [{"name": "Camera"}, {"name": "Phone"}]

app.include_router(router_item, prefix="/items",tags=["ITEMS"])
app.include_router(router_user, prefix="/users",tags=["USERS"])

Second Approach. Tagging Endpoints for Grouping

In the second approach, we leverage FastAPI's built-in tagging functionality to group endpoints based on their functionality. Tags are metadata that categorize endpoints, allowing for logical grouping and organization in API documentation.

Implementation

We define tags metadata containing information about user-related and item-related endpoints. Each endpoint function is tagged accordingly using the tags parameter in the decorator. For instance, endpoints related to users are tagged with "Users," and endpoints related to items are tagged with "Items." This tagging approach organizes endpoints based on their functionality and provides a structured view in the API documentation.

Here's an example of how you use tagging endpoints to group your API endpoints.

from fastapi import FastAPI

tags_metadata = [
    {
        "name": "Users",
        "description": "Users Detail.",
    },
    {
        "name": "Items",
        "description": "Items Detail.",
    },
]

app = FastAPI(openapi_tags=tags_metadata)


@app.get("/users/", tags=["Users"])
async def get_users():
    return [{"name": "Harry"}, {"name": "Ron"}]

@app.get("/users1/", tags=["Users"])
async def get_other_users():
    return [{"name": "Priya"}, {"name": "Riya"}]


@app.get("/items/", tags=["Items"])
async def get_items():
    return [{"name": "wand"}, {"name": "flying broom"}]

@app.get("/items1/", tags=["Items"])
async def get_other_items():
    return [{"name": "Camera"}, {"name": "Phone"}]

Output Image

Fast API

Conclusion

FastAPI offers multiple approaches for grouping API endpoints, each catering to different requirements and preferences. Whether using APIRouter for modular organization or leveraging tagging for documentation purposes, developers can choose the approach that best suits their project's needs. By adopting these techniques, developers can create well-structured APIs that are easy to maintain, understand, and use.


Similar Articles