Create a microservice API in under 50 lines

Athavan Karunakaran
4 min readMay 30, 2021
Photo by Joshua Reddekopp on Unsplash

Preface: There will be a point where you have a great idea, maybe it’s an app, maybe it’s a website. You may be a front-end developer or a back-end developer, or you may be new to coding altogether, and you just want the quickest solution to get your idea up and running. This will be one in a series of articles piecing together the basics of a modern framework so that whatever your idea is, you can make it a reality.

I’m a strong advocate for the microservice architecture, mostly because I believe that you should write most of the code in your app, and not rely on boilerplate code/configuration files. That way you completely understand what you’re building, which will also be helpful when you’re debugging it because something’s not working as expected.

That’s why I love Flask, and specifically, Flask RESTful because other than all the python libraries you install, the code for a working framework could be as simple as 1 file, allowing you to focus on what you really care about, which is building functionality.

The Flask API I’ve built below is for a chess game with a React frontend, you can find the complete source code, including all Python and React here, and you can actually play the game at https://minymal.app/

Without further ado, the 49-line RESTful API…

So now let’s break it down.

Imports

from flask import Flask
from flask_restful import Resource, Api, reqparse
from flask_cors import CORS
from waitress import serve
from updateboard import init_board, update_with_player_move, update_with_computer_move

We’ve imported a couple of libraries here:

  • flask: to set up the basics of the Web Framework
  • flask_restful: to add RESTful API functionality on top of Flask
  • flask_cors: to resolve any cors issues that may arise when calling our API
  • waitress: to provide a production-ready WSGI (more on this later)
  • updateboard: this is my own code, this is the actual logic of the API, taking parameters passed from the API and returning the output in the form of a dictionary

Initialization

app = Flask(__name__)
api = Api(app)
cors = CORS(app)

This is all the boilerplate code that you require, the first line initializes the Flask app, the second line adds API functionality, and the third line resolves possible CORS issues.

Define an Endpoint

api.add_resource(CPUMove, '/chess/api/cpumove')

This sets up an endpoint so that any call made to this URL

http://localhost:5000/chess/api/cpumove

will be routed to the CPUMove class that we set up.

Set Input Restrictions and Output Values

class CPUMove(Resource):    
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('fen', type=str, required=True)
self.parser.add_argument('level', type=int, required=True)
def put(self):
args = self.parser.parse_args()
fen = args['fen']
level = args['level']
return update_with_computer_move(fen, level)

So this is where the API call actually gets parsed.

First, we need to instantiate the CPUMove class as an instance of the Resource class (provided by Flask).

Then we add parameters that we need for this call to be completed successfully, if we mark the parameter as required, it will raise an error with the calling frontend if it does not provide it.

Then we specify with HTTP methods (GET, POST, PUT, DELETE) we’ll allow this endpoint to accept, we do this by naming the methods to this class to reference one of the methods, in the class above we only allow PUT commands.

Finally, after we have all the parameters we need, we pass them to our function to perform all of the logic that we need to get our response, and then we return that response as a dictionary. A dictionary, specifically so that when the response is returned from the API, values can be extracted from the response using the keys provided in the dictionary.

Running the API

if __name__ == '__main__':
serve(app, host='0.0.0.0', port='5000')
# app.run(debug=True)

As you can see, one of the lines is commented out and the other is not, this is for the two ways this app can run.

app.run(debug=True)

This is the default way to run the app, it is great for debugging and provides errors when code breaks within your app, but it is not recommended for running when you’re ready to deploy. So for that, you use:

serve(app, host='0.0.0.0', port='5000')

Which uses the serve function imported from waitress, a library used for this purpose, and it serves your app, but it’s not very verbose in its error messages, so it’s recommended to use only for deployment.

python app.py

Once everything’s set up, running the API is as simple as entering the command above in your terminal, just like running any other python file.

Calling the API

axios.put(`http://localhost:5000/chess/api/cpumove`, {
fen: this.state.fen,
level: this.props.level
})

Once you have the API running on your computer, referencing it in your front-end code could be as simple as the above. The code above is written in JS for React using the Axios library.

That’s all there is to it! You’ve built a very short, fully-functioning API — hope this takes you one step closer to making your dreams a reality.

--

--

Athavan Karunakaran

Coder and Automation Expert, Obsessed with being productive.