RESTful Web API with Flask
Introduction
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.
Description
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.
Installation
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)
We would see something like this:
Running on https://0.0.0.0:105
Press CTRL+C to quit
领英推荐
Working of the code line-by-line
Rules For Variables
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()
Creating an API Blueprint
|-flaky
|-app/
|-api_1_0
|-__init__.py
|-user.py
|-post.py
|-comment.py
|-authentication.py
|-errors.py
|-decorators.py
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')
# ...
?For more details visit:https://www.technologiesinindustry4.com/2022/01/restful-web-api-with-flask.html