How to Create Microservices with FastAPI

How to Create Microservices with FastAPI

Ah, microservices! They’re like the Lego blocks of the programming world—small, manageable, and incredibly versatile. And when you’re crafting these tiny titans, what better tool to reach for than FastAPI? It’s fast (duh!), it’s pythonic, and it’s got swagger (literally, with automatic API documentation). If you’re itching to break your monolith into microservices or just looking to dip your toes into the microservice architecture, you’re in the right place. Buckle up as we dive deep into creating microservices with FastAPI. We’ve got step-by-step instructions and examples that’ll have you up and running in no time. Ready to become a microservices maestro? Let’s get cracking!

Step 1: Setting Up Your Environment

First things first, you’ll need Python installed on your machine (Python 3.6+ is required for FastAPI). If you haven’t got it yet, head over to the Python website and follow the installation instructions for your operating system.

Before installing FastAPI create a new directory fast_examples and create a new virtual environment inside the newly created directory using virtualenv.
If you haven’t already installed virtualenv:

pip install virtualenv

Now, create a new virtual environment.

virtualenv env

If you are on Mac/Linux you can activate the virtual environment using the command:

source ./env/bin/activate

Windows users can run this command instead:

.\env\Scripts\activate

We’re going to install FastAPI and an ASGI server, Uvicorn, which will serve as our lightning-fast conduit to the web. Since FastAPI doesn’t come with inbuilt service, you need to install uvicorn for it to run. uvicorn is an ASGI server which allows us to use async/await features. Run the following command:

pip install fastapi uvicorn

Step 2: Your First FastAPI Microservice

Now, let’s get our hands dirty by writing our first microservice. Create a file named main.py in your project directory and open it in your favorite text editor. Paste in the following code:

from fastapi import FastAPI

app = FastAPI()

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

This snippet creates a basic FastAPI app that responds with {"Hello": "World"} when you navigate to the root URL. To fire up your server and see this in action, run:

uvicorn main:app --reload

Visit http://127.0.0.1:8000 in your browser, and voilà, your first microservice greets you.

Step 3: Adding More Endpoints

Microservices often need to handle various tasks. Let’s add another endpoint to our service that echoes back whatever is passed to it. Add the following code to your main.py:

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

Now, if you navigate to http://127.0.0.1:8000/yourname, replacing yourname with anything you like, the service will greet you by name.

Step 4: Using Path and Query Parameters

FastAPI makes it super easy to work with both path parameters (like the {name} we just used) and query parameters. Let’s add an endpoint that uses both. Add this to your main.py:

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

Now, accessing http://127.0.0.1:8000/items/3?q=somequery will show you how FastAPI handles both path parameters (item_id) and query parameters (q).

Step 5: Adding a Post Endpoint

Microservices often need to receive data, not just send it. Let’s create an endpoint to post data to our service. Update your main.py with:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/items/")
def create_item(item: Item):
    return {"name": item.name, "price": item.price}

This code snippet introduces a new concept: Pydantic models. These allow for easy data validation and settings management using Python type annotations.

Step 6: Testing Your Endpoints

Testing is crucial in software development, and FastAPI provides built-in support for testing with PyTest. Create a file named test_main.py and add some basic tests to ensure your endpoints are working as expected.

from fastapi.testclient import TestClient
from .main import app

client = TestClient(app)

def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"Hello": "World"}

Run your tests with pytest to make sure everything is shipshape.

Conclusion: The World of Microservices Awaits

And there you have it, folks—a basic but fully functional microservice built with FastAPI. You’ve seen how to set up your environment, create endpoints, work with parameters, accept data, and even write a simple test. But this is just the tip of the iceberg. FastAPI’s documentation is packed with more advanced features like dependency injection, security, and database integration that can help you build robust, efficient microservices.

Remember, the journey to microservice mastery is a marathon, not a sprint. Keep experimenting, keep learning, and most importantly, keep coding. The world of microservices is vast and varied, and it’s yours for the taking. Happy coding!

Leave a response to this article by providing your insights, comments, or requests for future articles.

Share the articles with your friends and colleagues on social media.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *