Flask API Tutorial: A Simple Guide for Beginners

Flask is a lightweight, easy-to-use web framework for building web applications in Python. One of its most common uses is to create RESTful APIs, which allow different software systems to communicate with each other over the web. In this simple tutorial, we’ll walk you through creating a basic Flask API step by step.

Flask is a microframework for Python, which means it provides the tools you need to build web applications but doesn’t come with the extra features that more extensive frameworks like Django offer. This makes it a great choice for smaller applications or APIs where you want to stay lightweight and have full control over the components you use.

Before you begin, make sure you have:

  • Python installed on your system (version 3.6+).
  • A basic understanding of Python programming.
  • Installed Flask, which you can do by running the following command in your terminal or command prompt:
pip install Flask

First, let’s start by setting up a simple Flask app. Create a new directory for your project, and inside it, create a Python file, app.py.

Here’s a basic example:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return "Hello, World!"

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

Explanation

  • Flask app instance: We create an instance of the Flask class, which represents our web application.
  • Route: The @app.route('/') decorator defines the URL (“/”) that the function hello_world will respond to. When someone accesses the root URL, it will return “Hello, World!”.
  • Debug mode: The debug=True enables Flask’s debugging features, which makes it easier to identify errors in your code.

To run the app, navigate to your project folder and run:

python app.py

Now, visit http://127.0.0.1:5000/ in your browser, and you should see “Hello, World!” displayed.

Now that we have a basic Flask app up and running, let’s extend it to include a simple API. For this, we’ll create a new route that responds to an HTTP request with JSON data.

Here’s how you can modify your app.py file:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def hello_world():
    return "Hello, World!"

@app.route('/api/data', methods=['GET'])
def get_data():
    data = {
        "message": "Welcome to my API",
        "success": True
    }
    return jsonify(data)

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

Explanation

  • jsonify: The jsonify() function converts a Python dictionary into a JSON response. This is essential for creating an API, as APIs typically exchange data in JSON format.
  • API route: We’ve created a new route /api/data that will respond to GET requests by returning JSON data with a message and success status.

To test this, restart your Flask app and go to http://127.0.0.1:5000/api/data in your browser. You should see something like this:

{
    "message": "Welcome to my API",
    "success": true
}

Step 3: Handling POST Requests

APIs often need to handle various types of requests, such as POST, which is commonly used to send data to the server. Let’s extend our Flask API to accept POST requests.

Modify your app.py as follows:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/')
def hello_world():
    return "Hello, World!"

@app.route('/api/data', methods=['GET'])
def get_data():
    data = {
        "message": "Welcome to my API",
        "success": True
    }
    return jsonify(data)

@app.route('/api/data', methods=['POST'])
def post_data():
    posted_data = request.get_json()  # Get the posted JSON data
    name = posted_data.get('name')

    response = {
        "message": f"Hello, {name}",
        "success": True
    }
    return jsonify(response)

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

Explanation

  • request.get_json(): This function retrieves the JSON data sent in the body of the POST request.
  • Dynamic response: We extract the name from the posted data and return a personalized message.

To test the POST request, you can use a tool like Postman or curl:

curl -X POST http://127.0.0.1:5000/api/data -H "Content-Type: application/json" -d '{"name":"John"}'

You should receive a JSON response like this:

{
    "message": "Hello, John",
    "success": true
}

It’s important to handle errors in your API to provide clear responses when things go wrong. Let’s add some basic error handling.

Here’s how you can update your post_data function to include error handling:

@app.route('/api/data', methods=['POST'])
def post_data():
    posted_data = request.get_json()

    if not posted_data or 'name' not in posted_data:
        return jsonify({
            "message": "Invalid input",
            "success": False
        }), 400  # 400 is the HTTP status code for "Bad Request"

    name = posted_data.get('name')
    response = {
        "message": f"Hello, {name}",
        "success": True
    }
    return jsonify(response)

Explanation

  • Input validation: We check if the name key exists in the posted data. If not, we return an error message with a 400 status code.
  • Error response: The jsonify() function is also used to send error responses, maintaining consistency in your API’s response format.

At this point, you have a fully functional Flask API that can handle both GET and POST requests, along with basic error handling.

To run the API, simply execute:

python app.py

Your API will be live at http://127.0.0.1:5000/, and you can interact with it using a browser or API testing tools.


In this tutorial, we covered the basics of creating a simple API using Flask. We started by setting up a basic Flask application, added API routes, handled both GET and POST requests, and incorporated basic error handling. Flask’s simplicity and flexibility make it an excellent choice for building APIs in Python, especially when you want to keep things lightweight.

By following this guide, you’ve now built your own Flask API and are ready to explore more advanced features such as authentication, database integration, and deploying your API to a live server.

1. How do I handle errors in Flask API?

You can handle errors by defining custom error handlers using the @app.errorhandler() decorator. This allows you to return specific error messages and status codes for different types of errors.

2. How can I test my Flask API?

You can test Flask APIs using tools like Postman or cURL for manual testing. For automated testing, you can use Python’s unittest framework along with Flask’s testing utilities such as FlaskClient.

3. How do I add authentication to a Flask API?

Authentication can be added using extensions like Flask-JWT-Extended for JWT authentication or Flask-OAuthlib for OAuth. You’ll need to configure and implement the authentication logic in your API routes.

4. What is Flask-RESTful?

Flask-RESTful is an extension for Flask that simplifies the creation of REST APIs. It provides tools for quickly building RESTful resources and handling common API tasks.

5. How do I handle JSON data in Flask APIs?

Flask can handle JSON data using the request object. To parse JSON data from a request, use request.get_json(), and to return JSON data, use jsonify() from the flask module.

Leave a Comment