Sunday, February 12, 2023

Write REST APIs IN PYTHON - ROUTER

 In FastAPI, a router is a mechanism for grouping a set of related endpoints and applying common functionality to all of them, such as prefixing their URLs or applying middleware to all requests to the endpoints.


Routers are created using the APIRouter class in FastAPI, which provides a convenient way to define multiple routes in a single place, and then include all of those routes in your main FastAPI application using the include_router method.

For example, if you have a set of endpoints for managing items in an e-commerce website, you could define all of those endpoints in a single file using an APIRouter and then include the router in your main FastAPI application. This would allow you to apply common functionality to all of those endpoints such as adding an authentication middleware to ensure that only authorized users can access the endpoints.

The main advantage of using routers in FastAPI is that they allow you to organize your application into smaller, more manageable parts making it easier to maintain and extend your code.

# File endpoints/items.py 

from fastapi import APIRouter

router = APIRouter()

@router.get("/{item_id}")

async def read_item(item_id: int, q: str = None):

         return {"item_id" : item_id, "q" : q}


@router.put("/{item_id}")

async def update_item(item_id: int, q: str = None):

         return {"item_id" : item_id, "item" : item}



# File main.py

from fastapi import FastAPI

from .endpoints import items 


app = FastAPI()

app.include_router(items.router, prefix="/items")














No comments:

Post a Comment