How to add a search endpoint in Flask

Extending a Flask web application with an API

Let’s assume that a Flask web application exists for which an API is needed. For the sake of this tutorial, we will assume the website is about fitness.

Search Endpoint

One of the main features of the API would be to allow searches for the content stored for certain topics.

app.py
workout_advice.yml
import PyYaml as yaml
@app.route("/api/search/<topic>", methods=['GET'])
def get_search(topic):
# Converting to suitable search
topic_modified = topic.replace(" ", "_").lower()
file_path = "{0}.yml".format(topic_modified)
# Reading file
with open(file_path, 'r') as yml_data:
# Converting yaml data to dictionary
data = yaml.load(yml_data)
return jsonify({'response': 200, 'results': data['posts']})

This example demonstrates how a Search Endpoint may be set up in Flask. The get_search method will need to be added to the app.py file.

The request receives the searched variable in topic. The get_search function is then called. Next, the search query is converted into the appropriate format, i.e., in lower-case with underscore characters (_) instead of spaces.

This program assumes that topic data is stored in YAML files. The program attempts to open the YAML file for the topic. Data is then read from the file, converted to a Python dictionary,and then into a JSON object for transmission.

The following example shows how resultant data will look when a client searches for workout advice.

{
"response": 200,
"results": [
{
"title" : "Important Workout Rules #1",
"content" : "Keep your back straight during all exercises."
}
]
}
Copyright ©2024 Educative, Inc. All rights reserved