Building a Simple API Route with Python Flask

Flask, a micro web framework for Python, provides an excellent platform for creating web applications and APIs quickly and efficiently. In this article, we’ll guide you through the process of building a simple API route using Flask.

Step 1: Install Flask

If you haven’t installed Flask, you can do so using pip. Open your terminal and run the following command:

pip install Flask

Step 2: Create a Flask App

Now, create a new Python file for your Flask application. Let’s call it app.py. Open the file and start by importing Flask:

from flask import Flask

app = Flask(__name__)

if __name__ == "__main__":
    app.run(debug=True)

This code initializes a Flask app.

Step 3: Create an API Route

Let’s create a simple API route that returns a JSON response. Update your app.py file:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/hello', methods=['GET'])
def hello():
    response = {"message": "Hello, Flask API!"}
    return jsonify(response)

if __name__ == "__main__":
    app.run(debug=True)

Here, we’ve defined a route /api/hello that responds to HTTP GET requests. When accessed, it returns a JSON response containing a greeting message.

Step 4: Run Your Flask App

Save your app.py file and run your Flask app:

python app.py

Your app should be running locally. Visit http://localhost:5000/api/hello in your browser or use a tool like Postman to send a GET request.

You should receive a JSON response like this:

{
    "message": "Hello, Flask API!"
}

Congratulations! You’ve created a simple API route using Flask.

Step 5: Further Enhancements

You can enhance your API by adding more routes, integrating a database, handling request parameters, or implementing authentication. Flask’s flexibility makes it easy to scale your application based on your needs.

Here’s an example of adding another route with a parameter:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/api/greet', methods=['GET'])
def greet():
    name = request.args.get('name', 'Guest')
    response = {"message": f"Hello, {name}!"}
    return jsonify(response)

if __name__ == "__main__":
    app.run(debug=True)

In this updated code, the /api/greet route takes an optional query parameter name. You can access it using request.args.get('name', 'Guest'). If the parameter is not provided, it defaults to ‘Guest’.

Flask’s documentation (http://flask.pocoo.org/docs/) is an excellent resource for exploring more features and possibilities.

Feel free to experiment and build upon this foundation to create powerful APIs with Flask. Happy coding!