Feedback

Chat Icon

Cloud-Native Microservices With Kubernetes - 2nd Edition

A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in Kubernetes

Deploying Stateless Microservices: Introduction
19%

Creating a Simple Stateless Microservice

In this section, we will create a simple stateless microservice using Flask, a lightweight web framework for Python. The microservice is a basic to-do application that allows users to add and retrieve tasks using an exposed REST API.

When using Python, a best practice is to create a virtual environment for each project to avoid changing the global Python environment needed by Linux or other applications. We are going to use virtualenvwrapper to create a new isolated environment for our project.

mkvirtualenv stateless-flask

Create the folders for our Flask application and install its dependencies.

# Create the project structure
mkdir -p stateless-flask
cd stateless-flask
# The app folder will contain the Flask application
mkdir -p app
# The kubernetes folder will contain Kubernetes manifests
mkdir -p kubernetes

# Install Flask
pip install Flask==3.0.3
# Add some dependencies to requirements.txt
cat << EOF > app/requirements.txt
blinker
click
Flask==3.0.3
importlib_metadata
itsdangerous
Jinja2
MarkupSafe
Werkzeug
zipp
EOF

The following Python code creates our simple Flask application. Use the heredoc syntax to create the file app/app.py.

cat << EOF > app/app.py
from flask import Flask, jsonify, request

app = Flask(__name__)

# Define a list of tasks
tasks = []

# route for getting all tasks
@app.route('/tasks', methods=['GET'])
def get_tasks():
    # Return the list of tasks as a JSON response
    return jsonify({'tasks': tasks})

# Route for getting a single task
@app.route('/tasks', methods=['POST'])
def add_task():
    # Create a new task from the request data
    task = {
        'id': len(tasks) + 1,
        'title': request.json['title'],
        'description': request.json['description'],
    }
    # Add the new task to the list of tasks
    tasks.append(task)
    # Return the new task as a JSON response
    return jsonify(task), 201

if __name__ == '__main__':
    app.run(
      debug=True,

Cloud-Native Microservices With Kubernetes - 2nd Edition

A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in Kubernetes

Enroll now to unlock all content and receive all future updates for free.