How To Build RESTful APIs with Python and Flask: The All-In-One Guide

Kajal Suthar
Python Features
Published in
5 min readMay 6, 2024
Build RESTful APIs with Python and Flask

In today’s world where there are 100’s of coding languages and 1000 available ways in which we can develop and design a digital solution, Python seems to be a preferred choice for a lot of people; after all, the language has its own advantages. It happens to be one of the fast growing languages surpassing ancient and known programming languages.

On platforms such as Github, it seems to be adopted by a lot of people, making it the 2nd used language in the year of 2023. With this increase in demand for Python users, there is also an increase in the need for efficient and scalable web services. Amongst all the available options across the internet, REpresentational State Transfer ( REST) has emerged as a popular Architectural style for design solution. Now, the question remains — what is this and how is it used? In simple words, REST is an architectural style that is used in modern development.

Speaking of development in Python, there are 3 options — Django, Flask and a relatively newer FAST API. But our interest lies in the Flask one. The next question would be what is Flask? Flask is a widely used micro web frame used to create APIs in Python. It is a very simple yet a powerful tool that is used for web frameworks where one can start off quickly and easily but has room to scale up in case of complexities. Given its lightweight feature, ease of usage, and widespread use, Flask seems to be a very good option to develop RESTful APIs. So, without further ado let us dive right in to how to develop RESTful APIs with Python and Flask.

Installing a Flask Application

Before you jump into creating REST APIs, the first and foremost step here is installation of some dependencies related to our development interests. And in this case, you have to install Python 3, PiP( Python Package Index), and Flask. If this process seems intense and complicated, you can always hire Python app developers; they will have the setup ready and will be able to build RESTful APIs with Flask and Python in no time.

Installing Python 3

If you are using the latest version of Linux or MacOS, you will find that Python 3 is already installed. However, Windows users will have to manually install Python 3; after all, this particular OS does not ship any of Python’s versions. After Installing Python, run this simple command to check the version of the Python installed on your machine:-

python --version

Installing Pip

You need Pip because it is the most preferred tool that developers use to install Python packages. Based on the official documentation pages, it looks like Pip comes bundled with Python 2 (version >= 2.7.9) and Python 3 (version >= 3.4). An important point to note is that if you are using the apt command to install Python on your Ubuntu machine, pip will not get installed automatically. Run this simple command to check whether pip is installed on your machine or not:-

pip --version

If this command returns something like pip 9.0.1 … (python 2.X), you can try replacing pip with pip3. In case this command does not return something like this, you will need to manually install Pip.

Installing Flask

We have briefly covered Flask’s capabilities in our introduction; so, let us move on to installing it on our machine and checking if we can get a basic Flask application running.

The first step to install Flask on your machine is to run this command in the terminal:-

pip install Flask

Once you have installed this package, create a file called hello.py and add the lines of code listed below to it; a point to note — you do not need to create a new directory as this file will simply check if Flask was correctly installed on your machine.

#hello.py
from flask import Flask

app = Flask(__name__) #There are two underscores before and after name

@app.route("/")
def hello_world():
return "Hello World"

This is all you need for a simple application that will handle HTTP requests and will return a “Hello World” message. To run this file and get the application running, simply execute the following command — flask — app hello run. Once the application has started running, open your browser and navigate to http://127.0.0.1:5000/ to see the message.

Important point to note — Ubuntu users might need to edit the $PATH variable to run Flask directly. You can do that using the following series of commands (execute these one by one):-

touch ~/.bash_aliases
echo "export PATH=$PATH:~/.local/bin">>~/.bash_aliases

How To Build RESTful APIs with Python and Flask?

Now that you have your setup ready, we can move on to seeing how you can build RESTful APIs with Python and Flask. We will be discussing two methods in which you can do this in no time — without using external libraries and by using the flask_restful library.

Method 1 — Without Using External Libraries

In this code, you will have two methods — one that just prints the data via GET or POST, and another that multiplies a number (sent through GET request) by 2 and prints it.

from flask import Flask, jsonify, request #imports all necessary libraries and functions

app = Flask(__name__) #creates a Flask app

@app.route('/', methods = ['GET', 'POST'])
def home():
if(request.method=='GET'):
data="hello world"
return jsonify({'data':data})

@app.route('/home/<int:num>', methods=['GET'])
def disp(num):
return jsonify({'data':num*2})

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

To execute the first method, simply type curl http://127.0.0.1:5000/ and you will be able to see the hello world message; for the second one, curl http://127.0.0.1:5000 / home / 10 and you will get 20 as the output.

Method 2 — Using flask_restful Library

The flask_restful library can be thought of as an extension of flask that is used by several companies offering expert Python web development services. Most developers use it because it encourages the use of best Python practices and is quite easy to set up. Before we move to the code, some background on flask_restful and how it works:-

So, the main building block in flask_restful is treated as a resource; and, every resource can have different methods like GET, POST, PUT, and DELETE attached with it. Every resource that you build is a class that gets inherited from flask_restful’s Resource class. As soon as you create a custom resource and define it, you can add it to the API and specify the URL path that corresponds to the resource. Now, let us move on to the code for a better demonstration:-

from flask import Flask, jsonify, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)
class Hello(Resource):
def get(self):
return jsonify({'message':'hello world'})

def post(self):
data=request.get_json()
return jsonify({'data': data}), 201 #201 is the status code

class Double(Resource):
def get(self, num):
return jsonify({'double':num*2})

api.add_resource(Hello, '/')
api.add_resource(Double, '/double/<int:num>')

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

You can test the output of this in the same way as we defined in Method 1 in the section above.

Conclusion

Now that we have discussed how you can build RESTful APIs with Python and Flask, we hope that you will utilize this to build simple but expert applications. If you need more clarity or are seeking expert help, we recommend you get in touch with X, a professional company offering expert Python web development services.

--

--