Showing posts with label rest api. Show all posts
Showing posts with label rest api. Show all posts

Friday

How to Work More Than One Developer in Single FastAPI Application

One FastAPI application however multiple developers can work simultaneously on different services. This approach uses separate service classes, routers, and a main application file.

Folder Structure

fastapi_app/

├── app/

│ ├── __init__.py

│ ├── main.py

│ ├── core/

│ │ ├── __init__.py

│ │ └── config.py

│ ├── services/

│ │ ├── __init__.py

│ │ ├── service1.py

│ │ ├── service2.py

│ │ ├── service3.py

│ │ └── service4.py

│ ├── routers/

│ │ ├── __init__.py

│ │ ├── router1.py

│ │ ├── router2.py

│ │ ├── router3.py

│ │ └── router4.py

│ └── models/

│ ├── __init__.py

│ └── models.py

└── requirements.txt

Example Code

app/main.py

from fastapi import FastAPI

from app.routers import router1, router2, router3, router4

app = FastAPI()

app.include_router(router1.router)

app.include_router(router2.router)

app.include_router(router3.router)

app.include_router(router4.router)

if __name__ == "__main__":

import uvicorn

uvicorn.run(app, host="0.0.0.0", port=8000)

app/core/config.py

class Settings:

PROJECT_NAME: str = "FastAPI Application"

VERSION: str = "1.0.0"

settings = Settings()

app/services/service1.py

class Service1:

def get_data(self):

return {"message": "Service 1 data"}

service1 = Service1()

app/routers/router1.py

from fastapi import APIRouter

from app.services.service1 import service1

router = APIRouter()

@router.get("/service1")

def read_service1():

return service1.get_data()

Repeat similar patterns for service2.py, service3.py, service4.py, and their corresponding routers.

Explanation

  • main.py: This is the entry point of your application. It includes all the routers.
  • core/config.py: Configuration settings for your application.
  • services/: Contains the service classes where the business logic resides.
  • routers/: Contains the routers that define the API endpoints and call the service methods.
  • models/: Contains the Pydantic models for request and response schemas.

This structure allows each developer to work on their respective service and router without conflicts, promoting modularity and maintainability.