Flask makes it very easy to create a RESTful web API. The known route() decorator besides its methods optional argument may be used to declare the routes. That controls the resource URLs exposed by the service. JSON data working is too simple. Because JSON data comprised with a request is automatically exposed as a request.json Python dictionary. A response that requires to contain JSON may be simply created from a Python dictionary using Flask’s jsonify() helper function.
In this article, we will learn how to create a RESTful web API with Flask.
Flask-RESTful is an extension for Flask. It provides help for fast building REST APIs. It is a lightweight abstraction, which does work with the existing libraries. Flask-RESTful supports best practices with minimal setup. Flask-RESTful should be simple to pick up if we are familiar with Flask.
Using pip install Flask-RESTful
pip install flask-restful
A Minimal Flask App
from flask import Flaskapp = Flask(__name__)@app.route('/hello/', methods=['GET', 'POST']) def welcome(): return "Hello World!"if __name__ == '__main__': app.run(host='0.0.0.0', port=105)
- Save this as api.py and run it using the python interpreter.
- Go to terminal and type
We would see something like this:
Running on http://0.0.0.0:105 Press CTRL+C to quit
- Launch any web browser.
- To look at the app in action, go to
Working of the code line-by-line
- Import the Flask class as
from flask import Flask
- Create an instance of the class as
app = Flask(__name__)
- We use the
route()decorator to ask the Flask what URL should trigger the function.
@app.route('/hello/', methods=['GET', 'POST'])
methodsindicates which HTTP methods are allowed. The default is
if __name__ == '__main__'→
__name__is a specific variable in Python.
- It takes the value of the script name.
- This line makes sure that our Flask app runs only when it is executed in the main file.
- It will not be executed when it is imported into some other file.
- Run the Flask application
hostindicates the server on which we want the flask application to run.
- The default value for
0.0.0.0show as all IPv4 addresses on the local machine.
- This makes sure that the server will be reachable from all addresses.
- The default
- We may set the parameter
portto use the port number of our choice.
Rules For Variables
- We can add variable sections to a URL by using
- The function gets the variable as a keyword argument.
from flask import Flask app = Flask(__name__)@app.route('/<int:number>/') def incrementer(number): return "Incremented number is " + str(number+1)@app.route('/<string:name>/') def hello(name): return "Hello " + nameapp.run()
- To start the Flask application run the above code.
- Open the browser and go to
- We will look at the output as
- The output will be
Incremented number is 11when we go to
Creating an API Blueprint
- The routes linked with a RESTful API form a self-contained subset of the application.
- Therefore, putting them in their own blueprint is the best way to keep them well organized.
- A common structure of the API blueprint within the application is shown in the below example.
|-flaky |-app/ |-api_1_0 |-__init__.py |-user.py |-post.py |-comment.py |-authentication.py |-errors.py |-decorators.py
- Note that how the package used for the API added a version number in its name.
- It can be included as another package with a different version number and both APIs may be served at the same time when a backward-incompatible version of the API requires to be introduced.
- This API blueprint applies each resource in a separate module.
- Modules are similarly added to take care of authentication, error handling, and to provide custom decorators.
- The blueprint constructor can be seen in the below example.
from flask import Blueprint api = Blueprint('api', __name__) from . import authentication, posts, users, comments, errors
The registration of the API blueprint may be seen in the following example.
def create_app(config_name): # ... from .api_1_0 import api as api_1_0_blueprint app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0') # ...