Complete guide to building Microservices using FastAPI

Posted by


Microservices have become increasingly popular in recent years as a way to build scalable and flexible applications. In this tutorial, we will show you how to build microservices using FastAPI, a modern web framework for building APIs with Python.

FastAPI is a high-performance web framework for building APIs with Python 3.6+ based on standard Python type hints. It is easy to use, fast, and efficient, making it a great choice for building microservices.

Before we start building our microservices with FastAPI, make sure you have Python installed on your machine. You can download and install Python from the official website. Once you have Python installed, you can install FastAPI using pip:

pip install fastapi

You will also need an HTTP server to run our FastAPI application. We will be using Uvicorn, a lightning-fast ASGI server implementation, to run our FastAPI application. You can install Uvicorn using pip:

pip install uvicorn

Now that we have installed FastAPI and Uvicorn, let’s start building our microservices. Create a new Python file and import the necessary modules:

from fastapi import FastAPI

Next, create an instance of the FastAPI class:

app = FastAPI()

Now, let’s define a simple endpoint that returns a JSON response. We will create a route decorator that maps a URL path to a function that handles the request:

@app.get("/")
def read_root():
    return {"Hello": "World"}

To run our FastAPI application, we need to start the Uvicorn server and pass our FastAPI application instance as a parameter:

uvicorn app:app --reload

This command tells Uvicorn to run the app.py file, where our FastAPI application instance is defined, and to reload the server whenever the code changes.

Now, if you open a web browser and navigate to http://127.0.0.1:8000, you should see a JSON response with the message "Hello, World!"

Next, let’s create another endpoint that accepts parameters in the URL path. We can define path parameters by including curly braces in the URL path and specifying the parameter name:

@app.get("/{name}")
def read_item(name: str):
    return {"Hello": name}

In this example, we define a path parameter called "name" that accepts a string value. When you navigate to http://127.0.0.1:8000/John, you should see a JSON response with the message "Hello, John!"

Now that we have created a simple API with FastAPI, let’s expand our application to include multiple microservices. We can organize our application by creating separate Python files for each microservice. Each microservice will have its endpoints and business logic.

For example, let’s create a new Python file called userservice.py to handle user-related operations. In this file, we can define endpoints for creating, reading, updating, and deleting users:

from fastapi import APIRouter

router = APIRouter()

@router.post("/create_user")
def create_user(username: str):
    # create user logic here
    return {"message": f"User {username} created"}

@router.get("/get_user/{user_id}")
def get_user(user_id: int):
    # get user logic here
    return {"user_id": user_id, "name": "John Doe"}

@router.put("/update_user/{user_id}")
def update_user(user_id: int, new_username: str):
    # update user logic here
    return {"message": f"User {user_id} updated with new name {new_username}"}

@router.delete("/delete_user/{user_id}")
def delete_user(user_id: int):
    # delete user logic here
    return {"message": f"User {user_id} deleted"}

To include the userservice in our main FastAPI application, we need to import the userservice module and include the router in our FastAPI application instance:

from fastapi import FastAPI
from userservice import router as user_router

app = FastAPI()

app.include_router(user_router)

Now, when you run the Uvicorn server and navigate to http://127.0.0.1:8000/docs, you should see the Swagger UI documentation for our FastAPI application, including the endpoints defined in the userservice.py file.

In this tutorial, we have shown you how to build microservices with FastAPI, a modern web framework for building APIs with Python. FastAPI makes it easy to create flexible and scalable applications with built-in support for asynchronous programming and type checking.

By dividing our application into separate microservices, we can create a modular and maintainable architecture that allows us to scale and evolve our application over time. FastAPI’s support for dependency injection, request validation, and automatic documentation generation makes it a powerful tool for building microservices.

We hope this tutorial has been helpful in getting you started with building microservices with FastAPI. Happy coding!

0 0 votes
Article Rating
34 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@darionstewart6237
2 months ago

Shoutout to you for not giving the same hello world tutorial that every other creator just copied and pasted off of the documentation

@kidjr.9520
2 months ago

For anyone facing problem in 2024 for involving response model install pydantic==1.10.13

@kshitijmathur1358
2 months ago

I am a huge fan of FreeCodeCamp. Unfortunately, it doesn't meet my expectations.

This isn't a proper and detailed microservices tutorial. I expected load balancing, reverse proxy, service discovery, containerization, orchestration, database architecture, message brokers, etc….

@fowobajek
2 months ago

Great tutorial. However when I try to replicate the tutorial on my windows machine, I got the error message "Error loading ASGI app. Could not import module "main"". Pls who can I resolve the error?

@liamlindy
2 months ago

Great high level introduction!

@user-uk2qm3cx4e
2 months ago

Why do you always have tutors with accent?

@ignazioolivieri3795
2 months ago

Good morning, I'm new – I wanted to ask you if it is appropriate to use Redis in case the relational data constantly changes due to the intervention of external users. That is, the tables are in use in real time so I don't know if it is valid to use Redis in this case and I don't know if it is possible to update a Redis register per sub key. Could you help me with a clarification? thanks

@angejoelziade6920
2 months ago

Excuse me but i didn't see where redis is needed.

@svenlampe5715
2 months ago

I can't figure out why I get this FastAPIError: Invalid args for response field! Hint: check that <class 'main.Product'> is a valid Pydantic field type. Has anyone an idea?

@oldstylegaming
2 months ago

i must be doing something wrong here but cant figure out what, when i di the initial post request i get an error back in postman "422Unprocessable Entity" like it cant access the fields….

@user-lo3zp3og7m
2 months ago

Thank you very much for the video it was very informative

@arturlinnik2128
2 months ago

I thought websockets where used to retrieve information about the pending and completed status and change the frontend instantly

@ashivnishekhawat6129
2 months ago

Great tutorial. If anyone is having troubles getting the redis account, note that you can also run a local instance using docker.

@elayechebouchareb3906
2 months ago

Thank you for your fabulous work.

Running in background does not work. I'm behind to make it work.

@nedupoetry3819
2 months ago

I have followed your procedure, but I keep getting this error

requests.exceptions.SSLError: HTTPSConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /products/01G9D4114WV4BSPGG5HV2MGKV0 (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)')))

@josephanolue329
2 months ago

hi thanks for this beautiful video, i have tried multiple times to connect both microservices but i keep getting this error i am going to post below…

requests.exceptions.SSLError: HTTPSConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /products/01G9D4114WV4BSPGG5HV2MGKV0 (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)')))

@victormendoza9163
2 months ago

My name is Antonio Papa but everybody calls me Antonio

@kyky6677
2 months ago

Thanks for the effort but I think this is a multiservices app rather than a microservices one. In microservices each service has its own server and its own database, and the biggest challenge in microservices architecture is how to deseign a database when it’s distributed

@Tigersoulification
2 months ago

Excellent tutorial guys. I was trying to keep it up on it but unfortunately I've got stock in the first consumer that comes from inventory. Whenever I sent the redis-stream it serves well the data but for some reason the Product.get() method does not work and tends to dispatch me that the product not exists while is already there. How could I solve that issue?

@a225855305
2 months ago

How to use it with RabbitMQ?