A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.imaginarycloud.com/blog/flask-python below:

How to Build a Flask API with Python: The Complete Guide

How to make a REST API using Python Flask?

This article will guide you through the first steps to create a REST API using Flask(🌶️).

‍

Below you can see the endpoints you’ll have by the end of the tutorial. The documentation presented is also generated by the application you will create!

‍

Screenshot of Flask endpoint documentation

‍

Technical requirements

You must have Python installed on the current machine. The code presented will consider Python3. If you want to use Python2 and/or are following this procedure in a Windows machine, please follow the instructions presented in the Flask installation guide.

‍

Let’s start by creating a directory to store the project. In the directory you want to have your project, run the following commands on the shell:

‍

We’ve created the flask_demo directory and moved it inside. Before starting to install dependencies, let’s create a virtual environment by running the following command:

‍

This will create a folder into your project with the name .venv. After that, we need to activate the respective environment by running:

‍

This means we are now considering the venv virtual environment when running any Python code. It might be important to specify the environment you are considering when running it in your IDE.

‍

Make sure you have the environment active before following the next steps. You can check if you are inside the environment by looking to the left side of the console. If there’s the virtual environment name inside parentheses, you’re good to go.

‍

If you want to deactivate the environment, just run the following command:
‍

‍

Setting Up Your Flask API Development Environment

Before you begin developing a Flask API, ensure you have Python installed. It's recommended to use a virtual environment to manage dependencies and keep your project isolated.

‍

Install the Flask package using pip (Python package installer):

‍

pip install Flask==2.3.3

‍

At the point of writing, the Flask stable version is 2.3.3. If you want to have the project specifications updated and aligned with this version, you can use a requirements.txt file instead of installing Flask manually. You can copy the file below to the root directory:

‍

Flask==2.3.3

‍

After that, you just need to run the following command:

‍

pip install -r requirements.txt

‍

Now we are ready to start developing our REST API.

‍

Hello World

The first endpoint code:

‍

### First Steps: Your Hello World Flask API
Here’s how to build your first minimal Flask REST API:

```python
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return {'message': 'Hello, World!'}

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

‍‍

This example sets up a basic endpoint that returns a JSON response. The app.run() function launches a development server that listens on port 5000 by default.

‍‍

What?! Is it that simple? Yes, it is! The code is done to have an application with an implemented endpoint. Now we simply have to define the Flask environment variables and see your application ?. Note that you need to be in the folder with the main.py file to run this commands.

‍

Access the link http://localhost:5000/basic_api/hello_world to see the classic message we all love.

‍

REST API with CRUD structure

Now that we have created our first endpoint, let’s get back to this application blog post's main purpose: Have the REST API with the basic CRUD structure. Let’s build an API that supports CRUD operations on a list of items. This is a common use case in web development and backend services.

‍

from flask import Flask, jsonify, request
app = Flask(__name__)

items = []

@app.route('/items', methods=['GET'])
def get_items():
    return jsonify(items)

@app.route('/items', methods=['POST'])
def add_item():
    data = request.get_json()
    items.append(data)
    return jsonify(data), 201

@app.route('/items/<int:index>', methods=['PUT'])
def update_item(index):
    data = request.get_json()
    items[index] = data
    return jsonify(data)

@app.route('/items/<int:index>', methods=['DELETE'])
def delete_item(index):
    item = items.pop(index)
    return jsonify(item)

‍

This simple REST API in Flask allows clients to manage a list of items using standard HTTP methods.

‍

Now, for each of the routes created different methods are allowed. The following endpoints are available:
‍

With this structure, you are ready to create an API with all the complexity you need. This is not the most scalable structure since you consider multiple validations for each route, and the structure is not rigid. In the next sections, we’ll cover a more scalable solution that allows easy documentation creation as you develop your endpoints.

‍

Another tool that is very useful and common to use in the development of APIs is Postman. If you’ve never used it, we recommend you try it and explore it! It is very powerful and will increase your development to the moon and beyond. 🚀

‍

Blueprints

Before we present other Flask strengths, let’s talk about blueprints. A blueprint is an object very similar to a Flask application object, but instead of creating a new one, it allows the extension of the current application. This might be useful if you want to create multiple versions of an API or simply divide services within the same application.

‍

We will use this class type to present different use case scenarios of a Flask application. Let’s convert the code above to be inserted into a blueprint and loaded into the main application.

‍

Create a new folder named blueprints to start inserting blueprint modules as we progress in the blog post. Inside it, create a folder named basic_endpoints and then a file named __init__.py:

‍

# blueprints/basic_endpoints/__init__.py
from flask import Blueprint, jsonify

basic_bp = Blueprint('basic_bp', __name__)

@basic_bp.route('/')
def hello():
    return jsonify({'message': 'Hello from a Blueprint!'})

‍

Now the main.py file just needs to load the created blueprint and register it to the application object:

‍

# main.py
from flask import Flask
from blueprints.basic_endpoints import basic_bp

app = Flask(__name__)
app.register_blueprint(basic_bp)

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

‍

Now you should have exactly the same endpoints but using the structure provided by Blueprints. This will make your application easier to manage and scale as it grows.

‍

Jinja Templates for Flask

As already stated, Flask is a very minimal framework; however, it relies on a handy tool: the Jinja template engine. This allows for rendering dynamic HTML templates. Although this is out of this blog post's scope, we will just give a small example to demonstrate the concept.

‍

The first thing you have to do is create the templates folder and inside this folder, insert the example.html file.

‍

‍

Note there are two variables in use in the template inside {{ }}. This is a special format to include Python code inside the template, allowing for dynamic content to be rendered. In this case, we have the top and bottom of the variable, which will be converted to text inside the <p> tag. Now that the template is created let’s load it using Flask. Let’s create a new blueprint in a different file to demonstrate this example:

‍

<!-- templates/example.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jinja Template Example</title>
</head>
<body>
    <p>{{ top }}</p>
    <p>{{ bottom }}</p>
</body>
</html>

‍

Note there are two variables in use in the template inside {{ }}. This is a special format to include Python code inside the template, allowing for dynamic content to be rendered. In this case, we have the top and bottom of the variable, which will be converted to text inside the <p> tag. Now that the template is created let’s load it using Flask. Let’s create a new blueprint in a different file to demonstrate this example:

‍

# blueprints/jinja_demo/__init__.py
from flask import Blueprint, render_template, request

jinja_bp = Blueprint('jinja_bp', __name__)

@jinja_bp.route('/jinja_template')
def jinja_example():
    top = request.args.get('top', 'Default Top Text')
    bottom = request.args.get('bottom', 'Default Bottom Text')
    return render_template('example.html', top=top, bottom=bottom)

‍

Do not forget to register this blueprint in the main.py file:

‍

# main.py
from flask import Flask
from blueprints.jinja_demo import jinja_bp

app = Flask(__name__)
app.register_blueprint(jinja_bp)

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

‍

Here we can see the definition of the top and bottom variables based on the query params sent in the URL. For example, if you go to http://localhost:5000/jinja_template?top=top_text&bottom=bottom_text you will get the following result:

‍

‍

Adding CSS

For the giggles, let’s add some CSS to the page we just created. Create the static folder with the file example.css inside.

‍

/* static/example.css */
body {
    font-family: Arial, sans-serif;
    text-align: center;
    background-color: #f9f9f9;
    margin-top: 50px;
}

p {
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

‍

After that, add the corresponding reference to the CSS file we just created by adding this head tag to the HTML file:

‍

<!-- templates/example.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jinja Template Example</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='example.css') }}">
</head>
<body>
    <p>{{ top }}</p>
    <p>{{ bottom }}</p>
</body>
</html>

‍

Go to http://localhost:5000/jinja_template?top=cancel%20the%20REST%20API%20creation&bottom=I%20have%20to%20watch%20this%20bird and you should see something like this:

‍

‍

There! You have your jinja crash course and a meme generator endpoint! Do not touch the Business Cat! You might be surprised with what you'll find...

‍


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4