How to Create APIs in Python Using Flask: GET and POST Method

A step-by-step guide to creating APIs in Python with Flask. Learn how to create GET and POST methods in minutes.

In this tutorial, I’ll show you how to create APIs in Python with Flask in a few simple steps. I’ll demonstrate how to create GET and POST methods in a few minutes.

how to create apis in python using flask

APIs play a pivotal role in the internet and modern information infrastructures. API, which stands for Application Programming Interface, encompasses a set of rules, protocols, and tools enabling software to communicate with each other. APIs facilitate structured and predefined interactions between two software systems, enabling them to exchange information or execute operations.

Consider this example: When you log in to your Medium account, you’re utilizing an API. Upon submitting the login form with your username and password, this information is swiftly transmitted to a server for validation. The server then verifies the credentials and sends back a response, granting you access upon successful validation. This exemplifies the functionality of an API.

There exist various types of APIs and multiple methods to implement them. Throughout this tutorial, I’ll guide you on constructing an API in Python using Flask, a widely used web framework for developing both websites and APIs. Specifically, we’ll create both a GET and a POST API. If the concepts of GET and POST seem unclear at the moment, don’t worry — I’ll provide detailed explanations later on.

Table of Contents:

  • Why create an API with Python
  • Flask for creating Python APIs
  • GET API in Python using Flask
  • POST API in Python using Flask

Why create an API with Python

We’ve discussed the significance of APIs in the context of the internet, yet we haven’t delved into how to create one using Python. Python stands out as a widely recognized programming language renowned for its simplicity.

The syntax of Python is clear and readable, making it ideal for developing and maintaining diverse software projects, including the construction of APIs. Moreover, Python boasts an extensive and highly active community, a crucial factor contributing to its widespread adoption in various software projects.

Flask for creating Python APIs

Flask serves as a micro-framework designed for developing web applications in Python. It embodies the characteristics of being lightweight, fast, simple, and flexible. Leveraging Flask enables the creation of intricate web applications, such as APIs.

Written in Python, Flask relies on the WSGI tool, a protocol system for Python web applications, and Jinja2, a Python-based template engine.

One of the standout attributes of Flask lies in its simplicity and extensive customization possibilities. With just a few lines of code, you can establish an API endpoint (referred to as a URL hosting the API) and seamlessly integrate an HTML template.

In the following sections, I’ll walk you through constructing both a GET API and a POST API using Python with Flask, all within a concise code block.

Note: To begin, ensure Flask is installed using pip install flask or conda install flask if you are using the conda virtual environment manager.

GET API in Python using Flask

The GET method is a type of API that retrieves information from a source using the HyperText Transfer Protocol (HTTP). This method is utilized to send a request to a server where request parameters are available in the URL as queries. An example of a GET request:

https://api.example.com/data?key1=value1&key2=value2

You are sending a request to the server regarding ‘key1’ with the value ‘value1’ and ‘key2’ with the value ‘value2’. Data and information are publicly available, and there is no necessity to send additional parameters to the server beyond those required for your query. For instance, credentials or certificates are unnecessary.

The GET method is also used when loading a website. In this section, we’ll create a GET API in Python using Flask to return a simple HTML page.

Let’s write the code! Save the following code as “app.py”:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/')
def index():
    return """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Congratulations</title>
    </head>
    <body>
        <div style="text-align: center; margin-top: 100px;">
            <h1>Congratulations, this is your first API endpoint!</h1>
        </div>
    </body>
    </html>
    """

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

Well, now simply launch the Flask application with the command flask run --app app and go to the URL http://127.0.0.1:5000. You'll see your first GET API in Python using Flask:

how to create apis in python using flaskThis is a very simple case but should be informative. We refer to the URL where the API is operational as the “endpoint”.

Let’s try to build a slightly more complex example. We will create a GET endpoint where we can request data using query parameters. The data within our “server” in the .py file will be:

data = [
    {"city": "Napoli", "country": "Italy"},
    {"city": "Pisa", "country": "Italy"},
    {"city": "Reykjavik", "country": "Iceland"},
    {"city": "Akureyri", "country": "Iceland"}
]

Now, we will create a section of our site at “/cities”. Remember that the Flask app still needs to be running. (use the command flask run --app app).

from flask import Flask, jsonify, request

app = Flask(__name__)

# Dati forniti
data = [
    {"city": "Napoli", "country": "Italy"},
    {"city": "Pisa", "country": "Italy"},
    {"city": "Reykjavik", "country": "Iceland"},
    {"city": "Akureyri", "country": "Iceland"}
]

@app.route('/cities', methods=['GET'])
def get_cities():
    return jsonify(data)

If you access this page, it will return all the cities from our dataset:

[
  {
    "city": "Napoli",
    "country": "Italy"
  },
  {
    "city": "Pisa",
    "country": "Italy"
  },
  {
    "city": "Reykjavik",
    "country": "Iceland"
  },
  {
    "city": "Akureyri",
    "country": "Iceland"
  }
]

What if we want to filter our data using parameters from the URL through a query? Well, we’ll need to add a few lines to our code. We’ll implement simple logic using conditional statements in Python. We’ll accept parameters from the query as follows:

  • Country
  • City
  • Both Country and City
  • None of the above

Therefore, we’ll create an if-then-else statement in this manner:

if city and country:
     filtered_cities = [c for c in data if c['city'] == city and c['country'] == country]
     return jsonify(filtered_cities)
elif city:
    filtered_cities = [c for c in data if c['city'] == city]
    return jsonify(filtered_cities)
elif country:
    filtered_cities = [c for c in data if c['country'] == country]
    return jsonify(filtered_cities)
else:
    return jsonify(data)

In that code, we can handle all possible combinations. If we apply a filter, we’ll receive the filtered data, otherwise, we’ll still get filtered data.

The complete new code will be:

from flask import Flask, jsonify, request

app = Flask(__name__)

data = [
    {"city": "Napoli", "country": "Italy"},
    {"city": "Pisa", "country": "Italy"},
    {"city": "Reykjavik", "country": "Iceland"},
    {"city": "Akureyri", "country": "Iceland"}
]

@app.route('/cities', methods=['GET'])
def get_cities():
    city = request.args.get('city')
    country = request.args.get('country')

    if city and country:
        filtered_cities = [c for c in data if c['city'] == city and c['country'] == country]
        return jsonify(filtered_cities)
    elif city:
        filtered_cities = [c for c in data if c['city'] == city]
        return jsonify(filtered_cities)
    elif country:
        filtered_cities = [c for c in data if c['country'] == country]
        return jsonify(filtered_cities)
    else:
        return jsonify(data)
    
if __name__ == '__main__':
    app.run(debug=True)

Let’s try an example: if we want to obtain an Italian city, we can use this URL: http://127.0.0.1:5000/cities?country=Italy

[
  {
    "city": "Napoli",
    "country": "Italy"
  },
  {
    "city": "Pisa",
    "country": "Italy"
  }
]

Great! But what if we want to input some data? To input user data, we can’t use the GET method. Until now, we’ve fetched data from a server or a URL without sending data, except for the parameters. If we want to send data, we’ll have to create a POST method.

POST API in Python using Flask

The POST method enables us to transmit information to a server. For instance, when we use a login form, we send our credentials to the server to verify their correctness and gain access to the service. This operation isn’t just about receiving data from the server; the user is also transmitting data to the server.

Consider this scenario: we want to add a new city to the dataset of cities on our website. How do we accomplish this? The answer lies in the POST method.

Let’s explore how we can create a POST API in Python using Flask. We have the option of utilizing the same endpoint or creating a new one. We’ve opted for the former for convenience, but the choice of method doesn’t matter.

Below is the code to implement this:

@app.route('/cities', methods=['POST'])
def add_city():
    new_city = request.json
    if 'city' in new_city and 'country' in new_city:
        data.append(new_city)
        return jsonify({"message": "City added successfully", "city": new_city}), 201
    else:
        return jsonify({"error": "City and country are required fields"}), 400

We will send a JSON (a simple Python dictionary) containing our new data, and this endpoint will append the new data to our cities dataset and return a message with a code. By incorporating these lines into our previous code, our Python file will look like this:

from flask import Flask, jsonify, request

app = Flask(__name__)

# Dati forniti
data = [
    {"city": "Napoli", "country": "Italy"},
    {"city": "Pisa", "country": "Italy"},
    {"city": "Reykjavik", "country": "Iceland"},
    {"city": "Akureyri", "country": "Iceland"}
]

@app.route('/cities', methods=['GET'])
def get_cities():
    return jsonify(data)

@app.route('/cities', methods=['POST'])
def add_city():
    new_city = request.json
    if 'city' in new_city and 'country' in new_city:
        data.append(new_city)
        return jsonify({"message": "City added successfully", "city": new_city}), 201
    else:
        return jsonify({"error": "City and country are required fields"}), 400

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

To send data using the POST method in Python, we need to execute several lines of code in a separate Python file. The code to execute a POST request in Python is as follows:

import requests

url = 'http://127.0.0.1:5000/cities'
data = {'city': 'Sevilla', 'country': 'Spain'}
x = requests.post(url, json = data)
print(x.text)

NB: Remember that the Flask app still needs to be running. (use the command flask run --app app).

Now, let’s attempt a POST request by adding city = ‘Sevilla’ and country = ‘Spain’. We’ll observe the following output:

{
  "city": {
    "city": "Sevilla",
    "country": "Spain"
  },
  "message": "City added successfully"
}

What happens if we now call our endpoint? Here’s the updated data:

[
  {
    "city": "Napoli",
    "country": "Italy"
  },
  {
    "city": "Pisa",
    "country": "Italy"
  },
  {
    "city": "Reykjavik",
    "country": "Iceland"
  },
  {
    "city": "Akureyri",
    "country": "Iceland"
  },
  {
    "city": "Sevilla",
    "country": "Spain"
  }
]

Excellent! We’ve successfully constructed a POST API in Python using Flask in just a few simple steps. Now, we can retrieve data from a URL or server using the GET method and also add new data using the POST method.

Final Thoughts

In this tutorial, I’ve demonstrated how to create APIs in Python using Flask. We discussed the significance of APIs in the web, why Python is a suitable choice for building them, and we’ve explored the creation of both GET and POST APIs in Python using Flask.

For further exploration on this topic, I recommend checking out this inspiring article: How To Process Incoming Request Data in Flask.

If you found this article informative and helpful, please consider sharing it with your friends and colleagues. Stay updated with new articles and updates by visiting my Medium and LinkedIn profiles. Until the next article, happy coding!

Continue Learning

Discover more articles on similar topics