Flask as a REST API

Flask as a REST API

Flask is a microframework for Python, which can be used in small to medium applications. It was developed by Armin Ronacher, who led a team of international Python enthusiasts called Poocco. Flask is based on the Werkzeg WSGI toolkit and the Jinja2 template engine.

Feature & Supports:

• Development server and debugger • Integrated support for unit testing • RESTful request dispatching • Uses Jinja templating • Support for secure cookies • Extensions available to enhance features desired

Let’s talk more about Flask REST API

What is REST? Before we started creating an API server we must need to know about REST a little bit. There is so much information is available on Google and my intention is not to duplicate the same.

I just want to share my basic view on REST. REST is a set of conventions taking advantage of the HTTP protocol to provide CRUD (Create, Read, Update, and Delete) behavior on things and collections of those things.

Flask support all major HTTP verb like PUT, DELETE, POST, and GET

Action HTTP Verb Description Create POST Create a new thing Read GET Collection/Read of thing Update PUT Update the existing information Delete DELETE Delete a thing

Let’s understand using a simple example.

from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
    app.run(debug=True)

Save the above file as an api.py extension and run using the below command.

$ python api.py

Now test your API and hit the endpoint you got out put as {"hello":"world"}

Let’s define ENDPOINTS for API We can define our API endpoint in a very simple way, let's understand using a simple example.

from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)

# Create a URL route in our application for "/test" endpoint
@app.route('/test')
def test():
    return {:key":"test end point"}
# If we're running in stand alone mode, run the application
if __name__ == '__main__':
    app.run(debug=True)

I hope you like the flask framework.

Have questions? Drop a comment