Swipe left or right to navigate to next or previous post

Building Microservices with Flask

12 Apr 2024 . category: Server . Comments
#Server #Guide

Comprehensive Guide on Microservices- Tapan BK

This is the part 2 of 2 of the microservices. If you are interested about basic of the microservices, please visit Comprehensive Guide on Microservices

What is Flask?

Flask is a lightweight and flexible web framework for Python, designed to make it easy to build web applications and APIs. It is classified as a micro-framework because it does not require any particular tools or libraries and has no dependencies on external libraries other than the Python standard library.

Flask is known for its simplicity, flexibility, and minimalistic design, making it an ideal choice for building small to medium-sized web applications, APIs, and microservices. It provides developers with the freedom to choose their preferred tools and libraries, allowing for a highly customizable and tailored development experience. Overall, Flask is a popular choice among Python developers for its ease of use and versatility in building web applications.

Flask provides developers with the essential tools and features needed to create web applications, including:

Routing:

Flask allows developers to define routes that map URL patterns to Python functions. This enables handling of HTTP requests and defining how the application responds to different URLs.

HTTP Request Handling:

Flask provides request and response objects, allowing developers to access data from incoming HTTP requests and generate appropriate responses.

Template Rendering:

Flask supports Jinja2 templating engine, which enables developers to create HTML templates with dynamic content by embedding Python code.

HTTP Methods Handling:

Flask supports various HTTP methods such as GET, POST, PUT, DELETE, etc., allowing developers to define handlers for different types of requests.

Session Management:

Flask includes built-in support for managing user sessions and cookies, making it easy to implement user authentication and session-based features.

Extension Ecosystem:

Flask has a rich ecosystem of extensions that provide additional functionality and integrations with third-party services. These extensions cover areas such as authentication, database integration, form validation, and more.

Development Server:

Flask includes a built-in development server that makes it easy to run and test applications locally during the development process.

Steps to build the Microservices using Flask

Step 1: Install Python

    • Visit the official Python website at https://www.python.org/.
    • Navigate to the Downloads section and choose the appropriate installer for your operating system (Windows, macOS, or Linux).
    • Download the latest version of Python, which should be prominently displayed on the website.
    • Run the installer and follow the on-screen instructions to install Python on your system.
    • During the installation process, make sure to check the box that says "Add Python to PATH" to ensure Python is added to your system's PATH environment variable.

Step 2: verify Python Installation

  • Once Python is installed, open a terminal or command prompt on your system.
  • Type python --version and press Enter to verify that Python is installed correctly. You should see the version number of the installed Python interpreter.

Step 4: Flask Installation

  • With Python installed, you can now install Flask using Python's package manager, pip.
  • Open a terminal or command prompt on your system.
  • Type pip install Flask and press Enter to install Flask. This command will download and install Flask and its dependencies from the Python Package Index (PyPI).
  • Wait for the installation to complete. Once finished, Flask should be installed on your system.

Verify Flask Installation:

  • To verify that Flask is installed correctly, you can create a simple Flask application and run it.
  • Create a new Python file (e.g., app.py) and open it in a text editor.
  • Copy the following code into the app.py file:
  •     
        from flask import Flask
        app = Flask(__name__)
        
        @app.route('/')
        def hello():
            return 'Hello, Flask!'
        
        if __name__ == '__main__':
            app.run(debug=True)
    
  • Save the file and close the text editor.
  • Open a terminal or command prompt and navigate to the directory where the app.py file is located.
  • Type python app.py and press Enter to run the Flask application.
  • Open a web browser and visit http://127.0.0.1:5000/ (or http://localhost:5000/) to see the message "Hello, Flask!" displayed, indicating that Flask is installed and running correctly.

Splitting the Application into Microservices

Now that we have a basic Flask application, let's split it into microservices. We will create two microservices: one for handling user authentication and another for managing product data.

Step 1: User Authentication Microservice

Create auth_service.py File:

Begin by creating a new Python file named auth_service.py.

Import Necessary Modules:

Import the required modules, including Flask for creating the web application and any other libraries needed for database interactions and validation.

Set Up Flask Application:

Initialize a Flask application instance.

Define Route for User Registration:

Create a route using Flask's @app.route() decorator to handle user registration requests.

Implement Registration Function:

Write a function that accepts user data from the request and stores it in the database. This function will handle the user registration process.

Add Error Handling and Validation:

Implement appropriate error handling and validation logic to ensure that user data is processed correctly. This may include checking for missing fields, validating email addresses, and handling database errors.

Here's a Python code template to illustrate these steps:


from flask import Flask, request, jsonify

app = Flask(__name__)

# Route for user registration
@app.route('/register', methods=['POST'])
def register_user():
    # Get user data from request
    user_data = request.json
    
    # Validate user data (e.g., check for required fields)
    if 'username' not in user_data or 'email' not in user_data or 'password' not in user_data:
        return jsonify({'error': 'Missing required fields'}), 400
    
    # Add additional validation logic as needed
    
    # Store user data in the database (placeholder)
    # Replace this with actual database integration code
    # Example: db.insert(user_data)
    
    return jsonify({'message': 'User registered successfully'}), 201

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

User In this code: We define a route /register using the @app.route() decorator to handle POST requests for user registration.

  • We define a route /register using the @app.route() decorator to handle POST requests for user registration.
  • The register_user() function extracts user data from the request, validates it, and stores it in the database (placeholder code).
  • Error handling is implemented to handle missing fields in the user data.
  • Finally, we run the Flask application if the script is executed directly.

Steps to create a product management Microservice

This service is used to create, read, update and delete product

Create product_service.py File:

Start by creating another Python file named product_service.py.

Set Up Flask Application:

Initialize a Flask application instance within product_service.py.

Define Routes:

Define routes for creating, reading, updating, and deleting product data using Flask's @app.route() decorator.

Implement Functions:

Implement corresponding functions to handle each operation, such as creating a product, retrieving product data, updating product information, and deleting a product.


from flask import Flask, request, jsonify
app = Flask(__name__)

# Dummy data as placeholder for database
products = [
{"id": 1, "name": "Product A", "price": 10.99, "quantity": 100},
{"id": 2, "name": "Product B", "price": 20.49, "quantity": 50}
]
next_id = 3  # ID for the next product to be added

# Create a new product
@app.route('/products', methods=['POST'])
def create_product():
    global next_id
    data = request.json
    new_product = {
    "id": next_id,
    "name": data["name"],
    "price": data["price"],
    "quantity": data["quantity"]
    }
    products.append(new_product)
    next_id += 1
    return jsonify({"message": "Product created successfully", "product": new_product}), 201


# Retrieve all products
@app.route('/products', methods=['GET'])
def get_all_products():
    return jsonify({"products": products})


# Retrieve a single product by ID
@app.route('/products/<int:product_id>', methods=['GET'])
def get_product(product_id):
    product = next((p for p in products if p["id"] == product_id), None)
    if product:
        return jsonify(product)
    else:
        return jsonify({"message": "Product not found"}), 404


# Update a product by ID
@app.route('/products/<int:product_id>', methods=['PUT'])
def update_product(product_id):
    data = request.json
    product = next((p for p in products if p["id"] == product_id), None)
    if product:
        product.update(data)
        return jsonify({"message": "Product updated successfully", "product": product})
    else:
        return jsonify({"message": "Product not found"}) , 404


# Delete a product by ID
@app.route('/products/<int:product_id>', methods=['DELETE'])
def delete_product(product_id):
    global products
    products = [p for p in products if p["id"] != product_id]
    return jsonify({"message": "Product deleted successfully"}), 200


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

In this code:

  • The microservice defines routes for creating, retrieving, updating, and deleting products.
  • Dummy data (products) is used as a placeholder for a database.
  • Each product has an ID, name, price, and quantity.
  • The next_id variable is used to assign IDs to new products.
  • The microservice runs on Flask's built-in development server when executed directly.

Communicating Between Microservices using requests

When communicating between microservices using Python, the requests library is commonly used for making HTTP requests. Here's an example of how you can use requests to communicate between microservices:

Let's say you have two microservices, Service A and Service B, and you want Service A to make a GET request to Service B:

Service A code (service_a.py):


import requests

def communicate_with_service_b():
    url = 'http://service-b-hostname:service-b-port/endpoint'  # Replace with actual URL
    response = requests.get(url)
    
    if response.status_code == 200:
        print('Response from Service B:', response.json())
    else:
        print('Error:', response.status_code)

if __name__ == '__main__':
    communicate_with_service_b()


Service B code (service_b.py):


from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/endpoint', methods=['GET'])
def get_data():
    data = {'message': 'Hello from Service B!'}
    return jsonify(data), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001)


  • Service A makes a GET request to the /endpoint endpoint of Service B using requests.get.
  • Service B responds with JSON data.
  • Service A receives the response and processes it.

Make sure to replace 'http://service-b-hostname:service-b-port/endpoint' with the actual URL of Service B. Also, ensure that both services are running and accessible to each other.

This example demonstrates a basic request-response communication pattern between microservices using the requests library in Python. You can expand upon this pattern to include handling different HTTP methods, passing data in requests, and handling responses more effectively based on your specific use case.

This is the end of 2 of 2 of the microservices. If you are interested about basic of the microservices, please visit Comprehensive Guide on Microservices which is part 1 of 2 on microservices


Tapan B.K. | Full Stack Software Engineer

Tapan B.K. is Full Stack Software Engineer. In his spare time, Tapan likes to watch movies, visit new places.