loading...

Create a simple REST API in python using Flask

kiani0x01 profile image Mateen Kiani Originally published at milddev.com on ・3 min read

What actually is a Rest API?

REST is an acronym for REpresentational State Transfer. A REST API defines a set of functions which are used to perform requests like GET, POST and PUT and receive responses via HTTP protocol.

This was just a brief intro on what a Rest API is. Let’s create a very simple rest api in python. For this tutorial we will use flask to create our API and the reason for that is its simplicity.

Step 1:

Install Flask using pip

pip install -U Flask

pip is a python package manager and is used to install any python package. To know more about pip follow this link.

Step 2:

Create a python file (for example file.py), open it in any text editor and write the following code

from flask import Flask  

app = Flask(__name__)  


@app.route('/')  
def home():  
    return "This is home"  


app.run(host="127.0.0.1", port="5000")

In this code we have imported flask and defined a function named home. Flask contains a built-in wrapper for generating routes in the form of @app.route(‘/’), where @app is the name of the object containing our Flask app. With this decorator present, Flask knows that the next line (sharing the same level of indentation) will be a function containing route logic.

Now run your python file using

python3 file.py

or

python file.py

On successful execution you will see a message like this in your terminal

Serving Flask app “rest” (lazy loading)

Environment: production

WARNING: This is a development server. Do not use it in a production deployment.

Use a production WSGI server instead.

Debug mode: off

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now when you open http://127.0.0.1:5000/ in your browser you will see that your rest api is working.

This is a very simple example. Now if you want to make a Post request you will have to do some more work also most of the rest APIs return json response so we will also cover that as we move ahead.

Rest Api with both GET and POST request

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


@app.route('/', methods=['GET', 'POST'])  
def home():  
    if (request.method == 'GET'):  
        return 'Recieved GET request at homepage'  
    else:  
        dataposted = request.data  
        return f'recieved a POST request at homepage with {dataposted}'  


app.run(host="127.0.0.1", port="5000")

To test whether post requests are working or not create another python file and name it whatever you want. I have named it request.py and written following code to make HTTP Post request.

import requests  

postData = "post data"  
recieve = requests.post('http://127.0.0.1:5000/', data=postData)  
print(str(recieve.text))

After execution you should get this output

recieved a POST request at homepage with post data

Creating multiple routes

To create another route simply decorate another method with @app.route(‘/[routeAddressHere]’)

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


@app.route('/', methods=['GET', 'POST'])  
def home():  
    if (request.method == 'GET'):  
        return 'Recieved GET request at homepage'  
    else:  
        dataposted = request.data  
        return f'recieved a POST request at homepage with {dataposted}'  


@app.route('/about', methods=['GET', 'POST'])  
def about():  
    if (request.method == 'GET'):  
        return 'Recieved GET request at aboutpage.'  
    else:  
        dataposted = request.data  
        return f'recieved a POST request at about page with {dataposted}.'  


app.run(host="127.0.0.1", port="5000")

you can test for multiple routes by either opening https://127.0.0.1:5000/about in your browser or by making post request using request.py file as mentioned before.

Return Json response

We can return json response by using jsonify method included in flask package.

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


@app.route('/', methods=['GET', 'POST'])  
def home():  
    if (request.method == 'GET'):  
        return jsonify(output = "this is json response")  


app.run(host="127.0.0.1", port="5000")

output:

json response

The post Create a simple REST API in python using Flask appeared first on Mild Dev.

You can mention your queries in the comments section.

Posted on by:

kiani0x01 profile

Mateen Kiani

@kiani0x01

Software developer and a Student.

Discussion

pic
Editor guide