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
How to Create Microservices with FastAPI
Creating microservices with FastAPI involves setting up small, independent services that can communicate with each other, usually over HTTP. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. Here's a step-by-step guide
3 min read
Multiprocessing in FastAPI
In this article, we are going to see what is multiprocessing, and how multiprocessing can utilize the system resources efficiently and can reduce the time taken to complete a big task. We will see the "concurrent.futures" module that is used for multiprocessing in FastAPI and then see how we can use
5 min read
Build Your Own Microservices in Flask
Nowadays Python is everywhere. This is majorly due to its simplicity and wide range of applications. Flask is a lightweight web framework for building web applications in Python. Creating microservices with Flask is straightforward. In this article, we will start with a basic "hello world" microserv
5 min read
API Gateway Patterns in Microservices
In the Microservices Architecture, the API Gateway patterns stand out as a crucial architectural tool. They act as a central hub, managing and optimizing communication between clients and multiple microservices. These patterns simplify complexity, enhance security, and improve performance, making th
11 min read
Top 8 Python Frameworks for MicroServices
Microservices architecture has gained immense popularity for developing scalable and maintainable applications. This architectural style allows developers to build applications as a collection of loosely coupled services, which can be developed, deployed, and scaled independently. Python, with its r
6 min read
Install Httpx using Python PIP
When working on the internet or building websites, it's important to have good tools to ask for information. HTTPX is one of these tools, and a lot of people like it because it's fast, flexible, and has many features. This article will explain what HTTPX is and show you simple steps to put it on you
3 min read
Build an AI Chatbot in Python using Cohere API
A chatbot is a technology that is made to mimic human-user communication. It makes use of machine learning, natural language processing (NLP), and artificial intelligence (AI) techniques to comprehend and react in a conversational way to user inquiries or cues. In this article, we will be developing
5 min read
Run the fast-api server using Pycharm
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. Returning an image is a common requirement in web development, and FastAPI makes it straightforward to do. another famous framework for doing the same is Flask, which is also Python-based. Pre-requisitePyChar
3 min read
Sending Email using FastAPI Framework in Python
Before jumping into the topic directly, let's have a small intro about the technologies we are going to use. As the name suggests, we will be using FastAPI, a Python language framework. FastAPI: FastAPI is a python framework to develop REST Apis. It is very easy to build, Â high performance, easy to
3 min read
FastAPI - Using GraphQL
FastAPI and GraphQL have become prominent players in the realm of API development, each bringing its unique set of advantages to the table. GraphQL, initially created by Facebook, distinguishes itself with its efficiency and flexibility in data retrieval. In contrast to traditional REST APIs, GraphQ
5 min read