Doing sub routing properly in FastAPI

tech kamar
2 min readDec 4, 2023

I will keep this short and brief to teach you how to have multiple files for API controllers as your project grows and still make things works smoothly in FastAPI.

So lets learn with an example.

Imagine you have an application serves with APIs for both Sales and Marketing team.

Here are those APIs

Now to have this, lets create two different controllers.

Namely sales_router.py and marketing_router.py

Here is sales_controller.py

from fastapi import APIRouter

sales_router = APIRouter(prefix='/sales')


@sales_router.get("/employees")
async def list_employees():
return [{"name": "Rick", "salary":50000}, {"name": "Morty", "salary":680000}]

@sales_router.get("/report")
async def get_sales_report(year:int):
if year == 2023:
return {"profit":100, "revenue":500}

Now will see marketing_router.py

from fastapi import APIRouter
from pydantic import BaseModel

marketing_router = APIRouter(prefix='/marketing')

class Lead(BaseModel):
name: str
phone: str
address: str

# Not using DB. So storing leads in-memory
all_leads = []

@marketing_router.post("/lead")
async def add_lead(lead_info: Lead):
all_leads.append({
"name": lead_info.name,
"phone": lead_info.phone,
"address": lead_info.address
})
return "OK"

@marketing_router.get("/leads")
async def get_all_leads():
return all_leads

Now to the main.py file

from fastapi import FastAPI
from sales_router import sales_router
from marketing_router import marketing_router

app = FastAPI()

app.include_router(sales_router, prefix="/api")
app.include_router(marketing_router, prefix="/api")

Also make sure that all files are present in the same directory like this

Lets start the server from terminal

uvicorn main:app --host 0.0.0.0 --port 8080

Now open browser and hit the url : http://0.0.0.0:8080/docs#/

and you can see all the APIs with proper routers

Swagger UI

Explanation

I have used APIRouter class instead of FastAPI to create routes.

using prefix=”/abcd” helps in defining sub routes in each of the files. So route starts with /api in the main.py and then /sales or /marketing based on what sub routes they prefer

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response

Recommended from Medium

Lists

See more recommendations