Building Python microservices is easier and faster with modern frameworks like FastAPI.
In this guide, we’ll walk through creating a Python microservice that returns a list of 10 random African countries using FastAPI. By the end of this tutorial, you’ll have a fully functional microservice that can return data about African countries, following best practices for scalable and maintainable code.
Step-by-Step Guide to Build the FastAPI Microservice
1. Setting up the Environment
To begin, ensure you have Python installed on your machine. Instead of installing dependencies globally, we’ll use a virtual environment for package management. Virtual environments allow you to isolate project dependencies, preventing conflicts with system-wide installations.
Steps to set up a virtual environment:
- Open your terminal and navigate to your project directory.
- Create a virtual environment by running the following command:
python3 -m venv venv
- Activate the virtual environment:
source venv/bin/activate
With the virtual environment active, install FastAPI by running:
pip install "fastapi[standard]"
You can check out the full video on setting up a virtual environment in the description of this article or through the YouTube video linked below.
2. Structuring the Project
A well-organized project structure is crucial for scalability and maintainability. We’ll set up a basic structure for this service that separates concerns like data and logic.
african_countries_service/
│
├── main.py # FastAPI entry point
└── data.py # Contains the hardcoded data for African countries
-
main.py
is where the FastAPI app is defined. -
data.py
holds the list of African countries and their details.
3. Coding the Microservice
Now, let’s move on to the implementation. We’ll start with the hardcoded data in data.py
, followed by setting up our FastAPI application in main.py
.
data.py
:
import random
# List of 10 hardcoded African countries with name, population, and capital
COUNTRIES = [
{'name': 'Nigeria', 'population': '180 million', 'capital': 'Abuja'},
{'name': 'Ghana', 'population': '80 million', 'capital': 'Accra'},
{'name': 'Kenya', 'population': '53 million', 'capital': 'Nairobi'},
{'name': 'South Africa', 'population': '59 million', 'capital': 'Pretoria'},
{'name': 'Egypt', 'population': '102 million', 'capital': 'Cairo'},
{'name': 'Morocco', 'population': '36 million', 'capital': 'Rabat'},
{'name': 'Ethiopia', 'population': '115 million', 'capital': 'Addis Ababa'},
{'name': 'Ivory Coast', 'population': '26 million', 'capital': 'Yamoussoukro'},
{'name': 'Uganda', 'population': '45 million', 'capital': 'Kampala'},
{'name': 'Senegal', 'population': '17 million', 'capital': 'Dakar'},
]
def get_random_countries(n=10):
"""Return a list of n random African countries."""
return random.sample(COUNTRIES, k=n)
Next, in main.py
, we define the FastAPI app and create a route that returns a list of random African countries.
main.py
:
from fastapi import FastAPI
from data import get_random_countries
app = FastAPI()
@app.get("/countries", response_model=list)
def read_countries():
"""
Returns a list of 10 random African countries.
"""
countries = get_random_countries()
return countries
Download the source
4. Best Practices for FastAPI Microservices
- Modularity : We keep the data separate from the logic, ensuring that the app is easily maintainable and extendable.
- Validation and Security : FastAPI allows for automatic request validation, though not required here, it’s best to follow this principle when accepting inputs.
- Documentation : FastAPI automatically generates OpenAPI documentation and provides a UI using Swagger.
5. Running the Application
Run the app with the following command:
fastapi dev main.py
By default, the service will be available at http://127.0.0.1:8000
.
6. Testing the API
To test the service, you can navigate to http://127.0.0.1:8000/countries
. You should see a JSON response with 10 random African countries, for example:
[
{"name": "Nigeria", "population": "180 million", "capital": "Abuja"},
{"name": "Uganda", "population": "45 million", "capital": "Kampala"},
{"name": "Kenya", "population": "53 million", "capital": "Nairobi"},
{"name": "Morocco", "population": "36 million", "capital": "Rabat"},
{"name": "Egypt", "population": "102 million", "capital": "Cairo"},
{"name": "Senegal", "population": "17 million", "capital": "Dakar"},
{"name": "Ivory Coast", "population": "26 million", "capital": "Yamoussoukro"},
{"name": "Ethiopia", "population": "115 million", "capital": "Addis Ababa"},
{"name": "Ghana", "population": "80 million", "capital": "Accra"},
{"name": "South Africa", "population": "59 million", "capital": "Pretoria"}
]
7. Auto-Generated API Documentation
FastAPI provides auto-generated interactive API documentation. You can access the Swagger UI at http://127.0.0.1:8000/docs
and ReDoc documentation at http://127.0.0.1:8000/redoc
.
Conclusion
In this tutorial, we built a Python microservice using FastAPI to return a list of 10 random African countries. FastAPI’s simplicity and performance make it a perfect choice for microservices. With auto-generated docs, input validation, and modularity, this approach is highly scalable and maintainable.
Thanks for reading…
Happy Coding!
The post Building a Python Microservice with FastAPI to Return Random African Countries appeared first on Innovate With Folasayo.
Top comments (0)