arundhaj

all that is technology

Routing in Python Flask and HTTP Methods

 

In this article and video, we’ll see how to write RESTful APIs using Python Flask for the required behavior.

The route decorator is used to define the behavior of APIs. It can be applied to a method or class. Below is the basic use of route.

@app.route('/user')
def users():
    return user_service.get_user_list()

Path Parameters

Path params is passed in the URL of the request like https://api.test-domain-name.com/project/b2713a81-e2da-429d-87ba-3d7a4a04975c which will be handled by the following route as shown below

@app.route('project/<uuid:id>')
def project(id):
    return project_service.get_project_detail(id)

Query Parameters

Query params can be accessed with request.args variable which is parsed from the URL of format https://api.test-domain-name.com/user?first_name=Arunkumar

from flask import request

@app.route('/user')
def users():

    user_filter = dict()
    # request.args itself is a dict, however, it is not a secure practice to use
    # request data without cleaning or escaping or validating.
    if 'first_name' in request.args:
        user_filter['first_name'] = request.args.get('first_name')
    if 'last_name' in request.args:
        user_filter['last_name'] = request.args.get('last_name')

    return user_service.get_user_list(user_filter)

HTTP Methods

Following are the most common HTTP methods, we may require to implement routes for:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE
  • OPTIONS

In Flask, requests method can be identified using request.method variable, as shown below

@app.route('/user', methods=['GET', 'POST'])
def users():
    if request.method == 'GET':
        return user_service.get_user_list()
    elif request.method == 'POST':
        return user_service.add_user()
    else:
        return 'Unsupported HTTP Method'

Class based routes can also be defined as below

from flask.views import MethodView

class UsersAPI(MethodView):
    def get(self):
        return user_service.get_user_list()

    def post(self):
        return user_service.add_user()

app.add_url_rule('/user', view_func=UserAPI.as_view('users'))

Requests and Response Headers

Following snippet shows how to access Request headers with request.headers variable and set Response headers

from flask import request, abort, make_response

@app.route('/user')
def users():
    auth_token = request.headers.get('Authorization', None)
    if auth_token or auth_service.validate(auth_token):
        abort(401)

    response = make_response(user_service.get_user_list())
    response.headers['Content-Type'] = 'application/json'

    return response

@app.after_request
def after_request(response):
    response.headers['X-CUSTOM-API-HEADER'] = 'CustomHeaderValue'
    return response

Hope this helps!

Comments