Implementing Microservices With FastAPI In Python

Microservices is a term that every Python developer comes across every once in a while. It provides a great base to help you build mobile applications. Microservices help you break down large applications into several applications, each with a different service or functionality.

If you are thinking about implementing microservices with FastAPI in Python, you’re at the right place! Let’s explore more about microservices and how you can use them with fast API in Python.

What Are Microservices?

An application has two different types of architecture. The first type is monolithic architecture. In this setup, all types of application services use the same database. There is no distinction according to the services of functionality.

The second type of architecture is the microservices architecture. It is called service-oriented architecture. Using this approach, you can break down your application into different types of services. Each service runs in a separate process. The database for every service is different and depends upon its nature.

Benefits Of Microservices

Here are some benefits of microservices.

  • Applications built using this architecture provide you with the freedom to build each service using different technologies.
  • The development team does not have to go with a single choice to build an application or start a project.
  • It’s much easier to control the application because each service runs a specific functionality. Microservices also make the application easy to understand, which is one of the most essential features of successful mobile apps for startups.

Disadvantages Of Microservices

Using microservices comes with a few drawbacks as mentioned below.

  • It can be difficult to maintain consistency in the application because there is a different database for each service.
  • Service splitting is often a very difficult task.
  • Your mobile application might become slower because different services use network interaction for communication. So, there are high chances of network latency.

Python is easy and one of the best tools to create microservices. Likewise, FastAPI offers a high-performance web framework to app developers. It has several features that make it a great choice for creating microservices in Python. An app built FastAPI Python framework is very versatile and scalable.

Implementing Microservices

Let us now take a look at how to implement microservices with FastAPI in Python.

1. Install FastAPI

The first step to implementing microservices is to install the API. You can use the pip tool to install it on your computer. Once you see the signal ‘pip install fast API’ you can proceed to the next step.

2. Install Uvicorn

You would need to install ‘Uvicorn’ to run the server. Again, you can use the pip to install the standard version of this tool.

Once you have installed these two tools, you are ready to implement microservices.

3. Create services

Now, you can create two simple services.

  • The first service would be auth_service. It will help you check if the token is correct.
  • The second service, information_ Service will answer all your questions.

Both of these services will be simple to understand and will help you with easy authentication in FastAPI.

4. Creation Of Auth Service

You can create the auth_service.py file. Add all the imports that are necessary for coding. Now, proceed to create the FastAPI app.

You only need to go to the POST login view. Here, you will see an authorization value that will decide the response of the view and come up with two possible outcomes.

These outcomes will be:

  • OK, if the authorization header shows “Merixstudio.”
  • UNAUTHORIZED, if the value on the authorization header shows something else.

Now, you can use Uvicorn to start the service on port 8001. Create the information service info_service.py. Once done, import wraps, Any, Callable FastAPI, header, response,JSONResponse, and other requests.

Now, you can build the FastAPI application and define the endpoint

5. Crafting An Information Service

Now that the authentication service is up and running, let’s create the information service.

Make a file called info_service.py and add these imports:

from functools import wraps
from typing import Any, Callable, Optional
import requests from fastapi import FastAPI, Header, Response
from fastapi.responses import JSONResponse

Next, let’s build the FastAPI application:

app = FastAPI()

Define the endpoint we’ll connect to in the authentication service:

LOGIN_ENDPOINT = “http://127.0.0.1:8001/login/”

Now, write a special Python decorator. It checks with the authentication service to see if a user can be authorized. If not, it throws an exception. If everything’s fine, the endpoint runs as usual:

def auth_required(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any):
try:
response = requests.post(url=LOGIN_ENDPOINT,
headers={“Authorization”: kwargs[“authorization”]},
response.raise_for_status()
return func(*args, **kwargs)
except requests.HTTPError as error:
return Response (status_code=error.response.status_code )
return wrapper

Now, let’s define the information endpoint. Notice the @auth_required decorator we made earlier:

@app.get(“/info/”)
@auth_required
def get_information(authorization: Optional[str] = Header(None)) -> JSONResponse:
return JSONResponse(content={“info”: “The answer is 42.”})

To start this service on port 8000, use Uvicorn:

uvicorn auth_service:app –reload –port 8000

6. Running the Microservices Together

Let’s use curl to make requests to the API. Starting with no headers:

curl http://127.0.0.1:8000/info/

You’ll see a 401 Unauthorized status, transferred from the authentication service. If you pass the correct header, you get a different response:

curl http://127.0.0.1:8000/info/ -i –header “Authorization: merixstudio”

And that’s all! You will have successfully implemented microservices with FastAPI in Python.

Wrapping It Up!

Implementing microservices with FastAPI in Python opens up a world of possibilities for developers. It introduces you to a robust and efficient framework. FastAPI’s performance is great and it is very simple to use. So, it is a compelling choice for microservices development.

As a developer, you can easily use the microservices architecture and FastAPI’s features to build top-performing applications.

Article contributed by Rohan Dalvi, an accomplished Digital Marketing Manager at Siddhatech. With a proven track record in crafting effective digital marketing strategies, Rohan specializes in SEO, SEM, and other marketing mediums. He has a strong history of assisting brands in enhancing their digital presence and achieving prominent search engine rankings. During his free time, Rohan keeps a close eye on trending campaigns, algorithm updates, and the latest digital marketing software. Outside of work, he finds joy in cooking and drawing. The article contains the opinions of the author who is presumed to be an industry insider. The Local Brand® does not endorse any advice, services or products suggested.

The following two tabs change content below.
The articles published under TLB Bureau are either written by our staff writers or are selected works from contributors who are featured by our publication and are published with permission of authors.