Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to handle malicious users and invalid requests in Flask

Hassan Azhar

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.

Security precautions and request validation

An important part of developing an API is ensuring that malicious users do not cause any harm via invalid requests.
import PyYaml as yaml
from import topics

@app.route("/api/search/<topic>", methods=['GET'])
def get_search(topic):
    if len(topic) == 0 or topic is None:
        return send_404()
    topic_modified = topic.replace(" ", "_").lower()
    file_path = "{0}.yml".format(topic_modified)
    # If the topic does not exist, return status code 404
    if topic_modified not in topics.keys():
        return send_404()

        # 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']})
                return send_404()
    # Return status code 404 if the file is not found
        return send_404() 

# Function to return response when no data is found
def api_return_404():
    return make_response(jsonify({'response': 404, 'results': 'Requested data not found.'}), 404)    

This example shows a more secure and error-tolerant program than the one in the Search Endpoint shot. The code in the search endpoint shot attempted to return the contents of whatever YAML file had the same name as that which was queried. This is obviously dangerous as malicious users could access any file they wanted, even if it would be undesirable for the website’s host, by entering an arbitrary path. Also, an error message will show when a file could not be found.

The code in this example checks if the queried topic is present in the topics dictionary variable, defined in the, before sending the requested data. If an invalid request is made by the user, the program returns a 404 error message. The error will be in the following form:

  "response": 404, 
  "results": "Requested data not found."




Hassan Azhar
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring