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 requirementsYou 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 EnvironmentBefore 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 WorldThe 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 structureNow 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. ð
â
BlueprintsBefore 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 FlaskAs 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 CSSFor 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