October 1, 2020

Tutorial Drive

AWS, SEO, SMO, Digital Marketing AND More

REST API using Python and Flask – Part 1

Python Flask REST API

Python Flask REST API

Definition

Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services.

Why We Need REST API

Think that you are working on one project where you have to leverage capabilities of other programming languages or already existing software. In this case, the REST API came to rescue and help you to easily do shake hand between two or more system or platforms.

So, now let’s get started to create our first REST API based python script using a microframework called “Flask”.

Prerequisite

You need python 3.x+ and pip installed in your system to run this REST API project

Installation

Install flask restful package using pip.

$pip install Flask-RESTful

That’s it, you’ve installed flask framework.

Now lest create one basic program and see how REST APIs works.

Step 1

Create a new file name: flask-restful.py

Step 2

Open this file in any IDE you like and add required packages:

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

Step 3

Name your app

app = Flask(name)
api = Api(app)

Step 4

Now, we will define our functions. This functions will take all requests based on defined in routes. We will see how to create routes in this tutorial post function development.

# Define functions
# Basic function to display message.
class printHelloWorld(Resource):
    # get request using GET HTTP method and print pre defined message
    def get(self):
        return {'message':'Hello World!!!'}

    # get request using POST HTTP method and print user input
    def post(self):
        your_message = request.get_json()
        
        # Here, after return, you can pass custom HTTP response code.
        return {'your message': your_message}, 200
                
# Basic function to get input from user and perform addition with same number
class calculation(Resource):
    def get(self, num):
        return {'result': num+num}

Step 5

Now, let’s create routes to use our functions using Web Interface using REST APIs. You can use any naming conversation which can be easy to understand and remember.
Like other programming languages, we do not need to define HTTP Request Method in routes. This can be easily managed from within a function only.

# Define routes
# Route to call "printHelloWorld" function.
api.add_resource(printHelloWorld, '/')

# Route to call "calculation" function with user input in "num" key.
api.add_resource(calculation, '/calculation/<int:num>')

Step 6 (Optional)

If you wish to keep your app in debug mode, place this code at the end of the file.

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

That’s it. You’ve created your first REST API using Python and Flask. Now let’s test our REST API.

Execute

Open a terminal window and navigate to file location where you’ve created this file and execute below command.

python flask-restful.py

and you will see output something similar to this:

* Serving Flask app "flask-restful" (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: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 121-043-709

Success, you now APIs are ready to serve our need.

Testing

You can use and REST API Client like Postman or Postwoman to test this APIs.
Open REST API Client and use our defined routes with localhost:5000 (Default) and check the output.

Conclusion

  • REST architectural pattern is basically lightweight in nature. So, when you have bandwidth constraints then prefer REST web service
  • Easy and fast to develop
  • Top sites like Twitter, Yahoo uses this pattern
  • Most social networking sites like facebook.com uses REST web services
  • Mobile App development growing rapidly and for their server interaction, it uses this REST pattern as it is faster in processing request/response data

What Next?

In next part, we will perfrom basic CRUD operation with MySQL.