Before the concept of microservices, developers used monolith architecture to develop applications, in which every part of the application is designed as interconnected and interdependent.
Monolith architecture runs the application components as tightly coupled. This means each component and its associated components must be present in order to execute the whole application. Each component is dependent on the other so if one component fails prematurely, the entire application will be affected and will fail to execute as expected.
As technology progresses, more development architectures are being designed to mitigate the disadvantages of monolith architecture. Microservices are among the most popular architectures that help developers avoid the monolith of interdependent components.
A microservice architecture (MSA) is a logical structure for designing an application involving loosely-coupled modular components called microservices. It allows you to build different components with unique capabilities. Each component is called a microservice.
Every microservice only focuses on a single and unique functionality. With microservice architecture, all the components are divided into separate modules. They communicate with each other using a well-defined interface. They communicate through APIs that are loosely-coupled; if one fails, it does not affect the whole system.
You will learn about the idea of microservice architecture in this tutorial and put it into practice by developing one using a Flask REST API.
Python 3 and PIP are installed on your computer.
Some basic understanding of how to write Python script.
Visual Studio Code is installed on your computer.
python3 -m venv venv
For macOS/Linux:py -3 -m venv venv
To start the environment and execute Flask, run:
For Windows:venv\Scripts\activate
For macOS/Linux:. venv/bin/activate
Installing Flask now is very straightforward as it only takes one command. Run the following PIP command to get Flask installed:pip install flask
To test if Flask has installed correctly, create an app.py
file inside the project directory and run this Flask hello world code block:
To run it:
set FLASK_APP=app.py
Followed by:flask run
Then open http://127.0.0.1:5000/
on your favorite browser. A hello world works version of Flask will be served on your browser.
pip install flask-restx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"movies_list": [
{
"title": "The Dare",
"year": 2020,
"cast": [
"Richard Short",
"Daniel Schutzmann",
"Harry Jarvis"
],
"image": "Your-image-url",
"description": "Evil Dead is some film."
},
}
Go ahead and add more data to the JSON file as described in the above structure. Use this data to mimic actual data that can be saved to a database.
1 2 3 4 5 6 7
from flask import Flask, Response, request, abort // import json dependencies from flask import JSON, jsonify from flask_restx import Api, Resource, fields
1
app = Flask(__name__)
Initialize Flask application entry point
1
api = Api(app)
Add a namespace factory. This registers resources for the current API instance.
1
ns_movies = api.namespace('ns_movies', description = 'Movies API')
1 2 3 4 5 6
f = open("./json.json", "r") loaded_json = json.load(f) movie_info = { f '{dct["title"]}-{dct["year"]}': dct for dct in loaded_json.get("movies_list") }
1
2
3
4
5
6
7
8
9
10
movie_data = api.model(
'Movie Data', {
"title": fields.String(description = "Title of movie", required = True),
"year": fields.Integer(description = "Year released", required = True),
"cast": fields.List(fields.String, description = "Cast of movie", required = True),
"image": fields.Url(description = "Image Url", required = True),
"description": fields.String(description = "Description of movie", required = True)
}
)
1
@ns_movies.route("/")
Add the data source
1
class movies(Resource):
Add the API get method
1
2
def get(self):
return jsonify(movie_info)
Define the API POST method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@api.expect(movie_data)
def post(self):
params = request.get_json()
if (t: = params.get("title", "")) and(y: = params.get("year", "")):
try:
new_id = f '{t}-{y}'
if new_id in movie_info.keys():
abort(status = 409, description = 'Already Exists.')
movie_info[new_id] = params
for p in params:
if p not in movie_data.keys():
raise KeyError
except:
abort(status = 400, description = 'Bad parameters')
else:
abort(status = 400, description = 'Missing Title or Year.')
return Response(status = 200)
This basically executes a POST method within your microservice to the JSON data. This mimics how you run the API and add the data to a database. The method has the need. This includes verifying the data being added by the POST method and checking any HTTP request status such as 400 and 200.
Create the access route
1
@ns_movies.route("/<string:id>")
Add the data source
1
class movies(Resource):
GET method to fetch a specific movie
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def get(self, id):
if id not in movie_info:
abort(status = 404, description = f "Movie '{id}' doesn't exists.")
return movie_info.get(id)
PUT to update specific movie details.
@api.expect(movie_info)
def put(self, id):
if id not in movie_info:
abort(status = 404, description = f "Movie '{id}' doesn't exists.")
if not(params: = request.get_json()):
abort(status = 400, description = 'No parameters')
for p in params:
if p not in movie_data.keys():
abort(status = 400, description = 'Bad parameters')
for p in params:
movie_info[id][p] = params[p]
return Response(status = 200)
DELETE method to delete a single movie
1
2
3
4
5
6
def delete(self, id):
try:
del movie_info[id]
except KeyError:
abort(status = 404, description = f "Movie '{id}' doesn't exists.")
return Response(status = 200)
1 2 3
if __name__ == "__main__": // run the app on localhost app.run(host = '0.0.0.0', debug = True)
Your MSA API is ready. Run it using flask run. You can now test the routes using your favorite API testing utilities.