Microservice in Python using FastAPI
Last Updated :
08 Jul, 2024
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.
Python
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.
Python
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.
Python
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.
Python
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.
Python
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"}
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.
Python
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.
Python
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.
Python
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.
Python
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.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read