Creating APIs in Python Flask

Craig Sykes 07-Jun-2023 16:28:31

Python Flask is a micro web framework for building web applications and Application Programming Interfaces (APIs), which is known for its lightweight and easy-to-use nature. Flask is a popular choice for building APIs because it is simple to get started with, yet powerful enough to handle complex projects. It allows developers to build APIs quickly and easily by providing a minimalistic and flexible structure. It also has a large and active community, which means plenty of resources and tutorials are available to help developers learn and use the framework. Additionally, it supports a wide range of web development needs, such as URL routing, request handling, and template rendering.

With Flask, you can also surface your data no matter where it is stored, and if you need to combine data from multiple locations into a single API, this is possible and simple to implement too.

Setting up the environment

You will first need to install Python on your system to set up a development environment for building Flask APIs. You can download the latest version of Python from the official website (https://www.python.org/downloads/).

Once you have Python installed, you can use the package manager pip to install Flask and other necessary dependencies. You can do this by running the following command in your terminal:

pip install flask

This will install the latest version of Flask and all its dependencies. Once installed, you can use pip to install the necessary packages.

You may also want to install additional packages such as flask-cors and flask-marshmallow, which are commonly used with Flask for handling cross-origin resource sharing and Marshmallow for data serialisation and validation, respectively.

It's important to note that you should always use the latest version of Flask and other dependencies and document the versions you are using in a requirements.txt file so that other developers working on the same project can easily set up their development environments.

That's it! You now have a development environment set up for building Flask APIs.

Creating a basic API

Creating a basic API using Flask is relatively straightforward. To start, you will need to import the Flask module and create a Flask application instance. You can do this by adding the following code to a new Python file, typically named app.py:

from flask import Flask, jsonify, request

app = Flask(__name__)

The __name__ argument is passed to the Flask class, which is used to find the root path of the application.

Next, you can define routes for your API using the @app.route decorator. A route is a URL path the application should respond to, and the decorator is used to define the function that should be called when a client requests that path.
For example, you can define a route for the home page with the following code:

@app.route('/', methods=['GET'])
def home():
    return jsonify({'message': 'Welcome to the Flask API'})

This code defines a route for the root URL (/) with the GET method and a function named home that returns a JSON object containing a message.

You can define another route for a greet page with the following code:

@app.route('/greet', methods=['POST'])

def greet():

   name = request.json['name']

   return jsonify({'message': f'Hello, {name}!'})

This code defines a route for the /greet URL with the POST method and a function named greet that takes in the name from the request body and returns a JSON object containing a message.

Finally, you will need to run the application to start the server. You can do this by adding the following code at the bottom of your app.py file:

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

This code checks if the file is being run directly and starts the server in debug mode.

Now you can start the server by running the command python app.py and test the API by sending a GET request to the home page and a POST request to the greet page with a JSON object containing the name.

That's it! You have successfully created a basic API using Flask. You can now add more routes, handle more complex request and response data, and build your application further.

Connecting the API to a database 

Now that we have built a flask APU, we can try connecting the API to a database. In this example, we are using PostgreSQL (you can use any database). You can follow the steps below:

Install PostgreSQL: You will need to install PostgreSQL on your system. You can download it from the official website (https://www.postgresql.org/download/

Install the Python library for PostgreSQL: You can use the package manager pip to install the psycopg2 library, which is a popular Python adapter for PostgreSQL. Run the following command in your terminal:

pip install psycopg2

Connect to the database: You can connect to the database by creating a connection object and providing the database name, user name, password, host, and port. You can add the following code to your app.py file:
import psycopg2

conn = psycopg2.connect(
database="your_database_name",
user="your_user_name",
password="your_password",
host="your_host",
port="your_port"
)

Create a cursor: To interact with the database, you need to create a cursor object by calling the cursor method on the connection object.

cur = conn.cursor()

Execute SQL statements: You can execute SQL statements using the execute method on the cursor object. For example, you can create a table named users with the following code:

cur.execute("CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))")

Commit changes: To make the changes permanent, you need to call the commit method on the connection object.

conn.commit()

Close the connection: Finally, you should close the connection when you are done using it.

conn.close()

That's it! You have successfully connected your Flask API to a PostgreSQL database. You can now use the connection object and cursor object to execute SQL statements and interact with the database.
 
Here is a complete code example:


from flask import Flask, jsonify, request
import psycopg2

app = Flask(__name__)

def connect_to_database():
    conn = psycopg2.connect(
        host="host_name",
        database="database_name",
        user="user_name",
        password="password",
    )
    return conn

@app.route('/', methods=['GET'])
def home():
    return jsonify({'message': 'Welcome to the Flask API'})

@app.route('/greet', methods=['POST'])
def greet():
    name = request.json['name']
    return jsonify({'message': f'Hello, {name}!'})

@app.route('/add-data', methods=['POST'])
def add_data():
    try:
        conn = connect_to_database()
        cursor = conn.cursor()

        data = request.json
        name = data['name']
        email = data['email']

        cursor.execute(
            "INSERT INTO users (name, email) VALUES (%s, %s)", (name, email)
        )

        conn.commit()

        return jsonify({'message': 'Data added successfully'})

    except (Exception, psycopg2.Error) as error:
        print("Error while connecting to PostgreSQL", error)

    finally:
        if(conn):
            cursor.close()
            conn.close()

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

This blog post provided an introduction to building APIs with Python Flask, a lightweight and flexible micro web framework. The process of setting up a development environment and creating a basic API was outlined, including importing the Flask module, defining routes, and starting the server. Additionally, the process of connecting the API to a PostgreSQL database was demonstrated, including creating a database connection and executing SQL statements to interact with the database.

For readers who want to learn more about building Flask APIs, there are many resources available, including the Flask documentation (https://flask.palletsprojects.com/en/1.0.x/), tutorials, and open source projects. Practising building different types of APIs and exploring the various features of Flask can also help deepen one's understanding and skills in building APIs with this framework.

Please contact our experts if you need any help or advice.