Microservice in Python using FastAPI
Microservices architecture is the approach to software development where the large application is composed of smaller, independent services that communicate over well-defined APIs. Each service can be focused on a specific business function and it can be developed, deployed, and scaled independently.
FastAPI is the modern, fast, web framework for building APIs with Python 3.6+ based on the standard Python type hints. It is designed to be easy to use, flexible and to provide high performance. With automatic interactive API documentation and Strong support for data validation, FastAPI is a good choice for building microservices.
Main Concept: Building Microservices with FastAPI
What is FastAPI?
FastAPI is the web framework for building APIs with Python 3.6+ that is based on the standard Python type hints. It can provide several features such as:
- It can automatically interact with API documentation with the Swagger UI and ReDoc.
- It can be a fast execution due to being based on Starlette and Pydantic.
- It can be data validation with Pydantic.
- It can be asynchronous support which allows for the handling of many requests efficiently.
- It can dependency injection for managing the dependencies cleanly.
Why use the FastAPI for Microservices?
- High Performance: FastAPI is one of the fastest Python frameworks available.
- Ease of Use: With the automatic data validation and interactive API docs, development is streamlined.
- Asynchronous: Built-in support for the async/await. making it suitable for modern and non-blocking applications.
- Scalability: Each microservices can be developed, deployed, and scaled independently.
Implementation of Building Microservices with FastAPI
Step 1: Create the Microservices
Create the User and Task microservices using FastAPI.Once create the microservices then the file structure looks like the below image.

Step 2: Implementation of user-service
database.py: Create the database class and it will saved as user-service/app/database.py and put the below code.
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# SQLite database URL
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
# Create the database engine
engine = create_engine(SQLALCHEMY_DATABASE_URL)
# Create a configured "Session" class
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Create a base class for declarative class definitions
Base = declarative_base()
# Dependency to get the database session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
models.py: Create the models class and it will saved as user-service/app/models.py and put the below code.
from sqlalchemy import Column, Integer, String
from .database import Base
# Define the Task model
class Task(Base):
__tablename__ = "tasks"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String)
routes.py: Create the routes class and it will saved as user-service/app/routes.py and put the below code.
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from . import models, schemas
from .database import get_db
# Initialize the router
router = APIRouter()
# Create a new task endpoint
@router.post("/", response_model=schemas.Task)
def create_task(task: schemas.TaskCreate, db: Session = Depends(get_db)):
db_task = models.Task(title=task.title, description=task.description)
db.add(db_task)
db.commit()
db.refresh(db_task)
return db_task
# Get a task by ID endpoint
@router.get("/{task_id}", response_model=schemas.Task)
def read_task(task_id: int, db: Session = Depends(get_db)):
db_task = db.query(models.Task).filter(models.Task.id == task_id).first()
if db_task is None:
raise HTTPException(status_code=404, detail="Task not found")
return db_task
schemas.py: Create the schemas class and it will saved as user-service/app/schemas.py and put the below code.
from pydantic import BaseModel
# Define the TaskCreate schema
class TaskCreate(BaseModel):
title: str
description: str
# Define the Task schema
class Task(BaseModel):
id: int
title: str
description: str
class Config:
orm_mode = True # Enable ORM mode to work with SQLAlchemy models
main.py: Create the main class and it will saved as user-service/app/main.py and put the below code.
from fastapi import FastAPI
from .database import engine
from .models import Base
from .routes import router as task_router
# Create all database tables
Base.metadata.create_all(bind=engine)
# Initialize the FastAPI app
app = FastAPI()
# Include the task router with the specified prefix and tags
app.include_router(task_router, prefix="/tasks", tags=["tasks"])
@app.get("/")
def read_root():
return {"message": "Welcome to the Task Service"}
from fastapi import FastAPI
from .database import engine
from .models import Base
from .routes import router as task_router
# Create all database tables
Base.metadata.create_all(bind=engine)
# Initialize the FastAPI app
app = FastAPI()
# Include the task router with the specified prefix and tags
app.include_router(task_router, prefix="/tasks", tags=["tasks"])
get("/") .
def read_root():
return {"message": "Welcome to the Task Service"}
Step 3: Run the User-Service
We can use the below command to run the user service.
uvicorn app.main:app --reload --port 8000
Refer the below image for running process.

Step 4: Test the User Service

Step 5: Implementation of the Task Service
database.py: Create the database class and it will saved as task-service/app/database.py and put the below code.
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
model.py: Create the model class and it will saved as task-service/app/model.py and put the below code.
from sqlalchemy import Column, Integer, String
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)
full_name = Column(String)
from sqlalchemy import Column, Integer, String
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)
full_name = Column(String)
routes.py: Create the routes class and it will saved as task-service/app/routes.py and put the below code.
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from . import models, schemas
from .database import get_db
router = APIRouter()
@router.post("/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
db_user = models.User(username=user.username, email=user.email, full_name=user.full_name)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
@router.get("/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(models.User).filter(models.User.id == user_id).first()
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return db_user
schema.py: Create the schema class and it will saved as task-service/app/schema.py and put the below code.
from pydantic import BaseModel
class UserCreate(BaseModel):
username: str
email: str
full_name: str
class User(BaseModel):
id: int
username: str
email: str
full_name: str
class Config:
orm_mode = True
from pydantic import BaseModel
class UserCreate(BaseModel):
username: str
email: str
full_name: str
class User(BaseModel):
id: int
username: str
email: str
full_name: str
class Config:
orm_mode = True
Step 6: Run the Task-Service
We can use the below for run the task service.
uvicorn app.main:app --reload --port 8000

Step 7: Test the Task Service

Conclusion
Building the microservices with FastAPI can be efficient and straightforward due to its high performance, ease of the use and modern features. By the following the principles of the microservices architecture and leveraging the FastAPI capabilities. We can develop the scalable and maintainable application. This article will covered the basic setup and implementation of the microservices using FastAPI and providing the solid foundation for the further development and customization.