How to build and deploy microservices with Python
A JWT is signed, not encrypted: anyone who has the token can read what's inside it, but nobody can change it without the secret key.
Microservices are a popular way to build large applications as a set of small, independent services, each responsible for one part of the business. They let teams develop, deploy, and scale each part on its own.
This article explains what microservices are, then walks you through building one with Python and Flask: a product catalog service with secure JWT authentication. Finally, you'll containerize it with Docker and deploy it to Sevalla. All the code was tested with Python 3.15, Flask 3.1, and PyJWT 2.15.
What are microservices?#
Microservices are small, independent services that together make up an application. Each one handles a specific business capability, such as products, orders, or payments, owns its own data, and communicates with the others through lightweight APIs or message brokers.
In a monolithic application, all features are built, deployed, and scaled as a single unit. In a microservice architecture, you can deploy and scale each service independently. For example, you can run more instances of a product catalog that gets a lot of traffic, without scaling the payment service.
Microservices offer several benefits:
- Independent scaling: You can add instances only for the services that need them.
- Independent deployment: Teams can update a service without redeploying the whole application.
- Technology flexibility: Each service can use the language, framework, and database that suit it best.
- Fault isolation: A failure in one service doesn't have to bring down the whole application.
But they also come with challenges:
- Operational complexity: You have many services to deploy, monitor, and debug. Tracing a request across several services is harder than following it through one application.
- Network communication: Services talk over the network, so you need to handle latency, timeouts, and failures between them.
- Cost: Each service needs its own resources, and running many services can cost more than one monolith, especially for small teams.
For small applications, a well-structured monolith is often simpler. Microservices pay off when your application and team grow large enough to benefit from splitting them.
How to build a microservice with Python#
Let's build a microservice for an ecommerce application. The application has several components, such as a product catalog, orders, and payments, and each one would be an independent service that communicates with the others over HTTP.
In this tutorial, you'll build the product catalog service with Flask. It fetches product data from DummyJSON, a free API with sample data, and returns it as JSON to authenticated users.
Prerequisites#
To follow along, you need:
- Python 3.10 or later.
- Docker, to containerize the service.
- Basic familiarity with Flask and the command line.
1. Create your project#
-
Create a folder for your project and go into it:
mkdir flask-microservice cd flask-microservice -
Create a virtual environment with Python's built-in venv module:
python3 -m venv .venv -
Activate the virtual environment. On macOS and Linux:
source .venv/bin/activateOn Windows, in PowerShell:
.venv\Scripts\Activate.ps1
2. Set up a Flask server#
Create a requirements.txt file in the project's root directory with these dependencies:
flask
requests
pyjwt
gunicornrequests fetches data from the product API, pyjwt creates and verifies JSON Web Tokens, and gunicorn is the production server you'll use in Docker. Install them with:
pip install -r requirements.txtNext, create a folder named services, and inside it, a file named products.py with a basic Flask app:
import os
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def home():
return jsonify({"message": "Hello, this is a Flask microservice"})
if __name__ == "__main__":
app.run(debug=True, port=int(os.environ.get("PORT", 5000)))This creates a Flask app with a single route that returns a JSON message. When you run the file directly, it starts Flask's development server, with debug mode on, on the port in the PORT environment variable, or 5000 by default. The development server is for local development only. In production, you'll run the app with Gunicorn.
3. Define the API endpoint#
Now add an endpoint that fetches products from DummyJSON and returns the fields your application needs. Add this code to products.py, above the if __name__ == "__main__": line, and add import requests to the imports at the top:
BASE_URL = "https://dummyjson.com"
@app.route("/products", methods=["GET"])
def get_products():
try:
response = requests.get(f"{BASE_URL}/products", timeout=5)
response.raise_for_status()
except requests.RequestException:
return jsonify({"error": "The product catalog is unavailable"}), 502
products = [
{
"id": product["id"],
"title": product["title"],
"brand": product.get("brand"),
"price": product["price"],
"description": product["description"],
}
for product in response.json()["products"]
]
return jsonify({"data": products})A few details make this endpoint robust:
- The
timeout=5argument stops the request from hanging forever if the product API is slow. Requests to other services should always have a timeout. - If the product API fails or returns an error, the endpoint responds with
502 Bad Gateway, which tells clients that an upstream service failed, instead of crashing. product.get("brand")returnsNonewhen a product has no brand. In DummyJSON's data, 15 of the first 30 products have no brand, soproduct["brand"]would raise aKeyErrorand crash the endpoint.
4. Test the microservice#
Start the development server:
flask --app services/products runThen request the /products endpoint with curl, or a client like Postman:
curl http://localhost:5000/productsYou get a list of 30 products:
{
"data": [
{
"brand": "Essence",
"description": "The Essence Mascara Lash Princess is a popular mascara known for its volumizing and lengthening effects. Achieve dramatic lashes with this long-lasting and cruelty-free formula.",
"id": 1,
"price": 9.99,
"title": "Essence Mascara Lash Princess"
},
...
]
}How to add authentication to a Python microservice#
Right now, anyone can call the endpoint. To protect it, you'll add authentication with JSON Web Tokens (JWTs), a widely used open standard for passing authentication information between clients and services.
A JWT is a compact token that contains claims, such as the user's ID and an expiry time, and a signature. The service signs the token with a secret key, and verifies the signature on every request. A JWT is signed, not encrypted: anyone who has the token can read what's inside it, but nobody can change it without the secret key. So never put passwords or other secrets in a token.
Here's how the authentication flow works:
- The client sends a username and password to an
/authendpoint. - If they're correct, the service returns a signed JWT that expires after 30 minutes.
- The client sends the token in the
Authorizationheader of every request, asBearer <token>. - The service verifies the token's signature and expiry before it returns any data.
1. Store the users#
In a real application, users would be stored in a database, or managed by a separate authentication service. To keep this example simple, store them in a users.json file in the project's root directory.
Never store plain-text passwords. Store a hash instead, which you can check a password against but can't turn back into the password. Flask depends on Werkzeug, which includes password hashing functions. Run this command to create users.json with a user named admin and the password change-me:
python3 -c "
import json
from werkzeug.security import generate_password_hash
users = [{'id': 1, 'username': 'admin', 'password_hash': generate_password_hash('change-me')}]
json.dump(users, open('users.json', 'w'), indent=2)
"The file now contains the user and their password hash:
[
{
"id": 1,
"username": "admin",
"password_hash": "scrypt:32768:8:1$3mIkWVdpqbGyGWAl$4755..."
}
]When you're ready to store users in a database, Sevalla's Database Hosting runs managed PostgreSQL, MySQL, MariaDB, and Redis.
2. Set a secret key#
The service signs tokens with a secret key, which must stay the same across restarts and across every instance of the service. Otherwise, a token signed by one instance would be rejected by another. So read it from an environment variable instead of generating it in the code.
Generate a random key, and set it as the JWT_SECRET environment variable in your terminal. On macOS and Linux:
export JWT_SECRET=$(python3 -c "import secrets; print(secrets.token_hex(32))")On Windows, in PowerShell:
$env:JWT_SECRET = python -c "import secrets; print(secrets.token_hex(32))"3. Add the authentication code#
Replace the contents of services/products.py with the complete service:
import json
import os
from datetime import datetime, timedelta, timezone
from functools import wraps
from pathlib import Path
import jwt
import requests
from flask import Flask, jsonify, request
from werkzeug.security import check_password_hash
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ["JWT_SECRET"]
BASE_URL = "https://dummyjson.com"
TOKEN_LIFETIME = timedelta(minutes=30)
USERS = json.loads(Path(__file__).parent.parent.joinpath("users.json").read_text())
@app.route("/")
def home():
return jsonify({"message": "Hello, this is a Flask microservice"})
@app.route("/auth", methods=["POST"])
def authenticate_user():
data = request.get_json(silent=True)
if not data:
return jsonify({"error": "Send the username and password as JSON"}), 400
user = next((u for u in USERS if u["username"] == data.get("username")), None)
if not user or not check_password_hash(user["password_hash"], data.get("password", "")):
return jsonify({"error": "Invalid username or password"}), 401
now = datetime.now(timezone.utc)
token = jwt.encode(
{"sub": str(user["id"]), "iat": now, "exp": now + TOKEN_LIFETIME},
app.config["SECRET_KEY"],
algorithm="HS256",
)
return jsonify({"token": token, "expires_in": int(TOKEN_LIFETIME.total_seconds())})
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return jsonify({"error": "Authorization token is missing"}), 401
token = auth_header.removeprefix("Bearer ")
try:
payload = jwt.decode(token, app.config["SECRET_KEY"], algorithms=["HS256"])
except jwt.ExpiredSignatureError:
return jsonify({"error": "Authorization token has expired"}), 401
except jwt.InvalidTokenError:
return jsonify({"error": "Authorization token is invalid"}), 401
return f(payload["sub"], *args, **kwargs)
return decorated
@app.route("/products", methods=["GET"])
@token_required
def get_products(current_user_id):
try:
response = requests.get(f"{BASE_URL}/products", timeout=5)
response.raise_for_status()
except requests.RequestException:
return jsonify({"error": "The product catalog is unavailable"}), 502
products = [
{
"id": product["id"],
"title": product["title"],
"brand": product.get("brand"),
"price": product["price"],
"description": product["description"],
}
for product in response.json()["products"]
]
return jsonify({"data": products})
if __name__ == "__main__":
app.run(debug=True, port=int(os.environ.get("PORT", 5000)))Here's what the new code does:
app.config["SECRET_KEY"]reads the secret key from theJWT_SECRETenvironment variable. If it isn't set, the app refuses to start, so it never runs with a missing or weak key.- The
/authendpoint reads the JSON body withrequest.get_json(silent=True), which returnsNoneinstead of raising an error if the body isn't valid JSON. It finds the user and checks the password against the stored hash withcheck_password_hash(). If they match, it creates a token with the user's ID as the subject (sub), the time it was issued (iat), and an expiry time (exp), 30 minutes later. - The
token_requireddecorator reads the token from theAuthorizationheader and verifies it withjwt.decode(). PyJWT checks both the signature and the expiry time. It rejects expired tokens withExpiredSignatureError, and tampered or malformed tokens withInvalidTokenError. Thealgorithms=["HS256"]argument makes sure the service accepts only tokens signed with the algorithm you expect. - The
/productsendpoint now uses the decorator, so only users with a valid token can call it. The token stays inside your service: the request to DummyJSON doesn't include it, because you should never forward users' credentials to a third-party API.
4. Test authentication#
Restart the development server, and request the products without a token:
curl http://localhost:5000/productsThe service rejects the request with a 401 Unauthorized status:
{
"error": "Authorization token is missing"
}Now log in with the admin user's credentials:
curl -X POST http://localhost:5000/auth \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "change-me"}'The service returns a token:
{
"expires_in": 1800,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}Send the token in the Authorization header to get the products, replacing <token> with your token:
curl http://localhost:5000/products -H "Authorization: Bearer <token>"This time, you get the list of products. If you change a single character of the token, the service responds with Authorization token is invalid, and after 30 minutes, it responds with Authorization token has expired.
How to containerize the microservice with Docker#
Docker packages your service and its dependencies into an image, so it runs the same way on your computer and in production. Each microservice usually runs in its own container, which makes it easy to deploy and scale independently.
Create a Dockerfile in the project's root directory:
FROM python:3.15-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1 PORT=8080
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
USER nobody
EXPOSE 8080
CMD ["gunicorn", "--workers", "2", "services.products:app"]Here's what each instruction does:
FROMuses the official Python 3.15 slim image as the base.WORKDIRsets /app as the working directory inside the container.ENVsetsPYTHONUNBUFFERED, so logs appear immediately, and the default port,8080.COPY requirements.txtandRUN pip installinstall the dependencies. Copying requirements.txt before the rest of the code lets Docker reuse this layer when only your code changes.COPY . .copies your code into the image.USER nobodyruns the service as an unprivileged user instead of root.EXPOSEdocuments the port the service listens on.CMDstarts the app with Gunicorn, a production WSGI server, with two worker processes. When thePORTenvironment variable is set, Gunicorn listens on0.0.0.0at that port, so it's reachable from outside the container.
Next, add a .dockerignore file, so your virtual environment and other local files aren't copied into the image:
.venv
__pycache__/
.git
.envBuild the image:
docker build -t flask-microservice .Then run a container, passing the secret key as an environment variable:
docker run -p 8080:8080 -e JWT_SECRET="$JWT_SECRET" flask-microserviceThe service is now available at http://localhost:8080. Log in with /auth and request /products the same way as before, using port 8080. Because the secret key comes from the environment, a token issued by one Gunicorn worker is accepted by the other.
How to deploy the microservice to Sevalla#
Sevalla can build your microservice straight from its Dockerfile:
- Push your code, including the Dockerfile, .dockerignore, and users.json, to a Git repository on GitHub, GitLab, or Bitbucket. Don't commit your secret key.
- In the Sevalla dashboard, click Applications in the sidebar, then click Create > Application.
- Under Source, click Private repository, then choose your Git provider, repository, and branch. Choose a data center and a size, and click Create application.
- On the application's Settings tab, in the Build strategy section, click Update build strategy. Click Dockerfile, keep the default Dockerfile path and Docker context, then click Update build strategy.
- On the Environment variables tab, add a
JWT_SECRETvariable with a long random value, such as the output ofpython3 -c "import secrets; print(secrets.token_hex(32))". It's only needed at runtime. - On the Overview tab, click Deploy now, then click Deploy.
Sevalla sets the PORT environment variable for the web process, and Gunicorn listens on it automatically. When the deployment finishes, test the service with the same curl commands, using your application's domain instead of localhost. For more details, see the docs on building from a Dockerfile.
Summary#
Microservices let you build an application as a set of small services that you can develop, deploy, and scale independently. In this article, you built a product catalog microservice with Python and Flask, secured it with JWT authentication, containerized it with Docker, and deployed it to Sevalla.
Along the way, you applied practices that matter for any production service: storing password hashes instead of passwords, keeping the secret key out of the code, giving tokens an expiry time, setting timeouts on calls to other services, and running a production server as a non-root user.
As your application grows, you can add more services, such as orders and payments, and deploy each one as its own application on Sevalla's Application Hosting, connected to managed databases over a private network.