-1

My REST API knowledge is not up to date. When we apply filters or sorting when implementing a REST API, I know that we used to put ? and & to the endpoint like below:

/actors?attr={attr_value} Example: /actors?name=”Bob”

Filters out all actors that don’t have “Bob” in their name (Should allow for similar filtering for any other attribute)

However, when I see Flask examples, I've never seen someone adding those parameters to the endpoint like

@app.route("/api/v1/actors?gender=<gender>", methods = ['GET'])
    def get_player(gender):
        ....

What is the right way of applying filters or sorting when implementing a REST API with Flask?

Dawn17
  • 7,825
  • 16
  • 57
  • 118

1 Answers1

1

For simple GET requests there are to ways to pass query parameters:

  1. as path parameter
  2. as query parameter

GET requests with body are possible, but mostly considered bad practice.

The following example provides two endpoints with an example each.

import json
import flask
from flask import Flask
from flask import request

app = Flask(__name__)


# GET http://0.0.0.0:5000/api/v1/actors?gender=male
@app.route("/api/v1/actors", methods = ['GET'])
def get_players():
    if request.args['gender'] == 'male':
        return json.dumps([{ 'id': 23, 'gender': 'male' }], indent=2)
    else:
        return json.dumps([])


# GET http://0.0.0.0:5000/api/v1/actors/john/
@app.route("/api/v1/actors/<actor_id>/", methods = ['GET'])
def get_player_by_id(actor_id):
    return json.dumps({ 'id': actor_id, 'gender': 'male' }, indent=2)


app.run()

I am not going to explain REST here, but the return values and endpoint structure should give you an idea.

Markus Rother
  • 414
  • 3
  • 10