Tutorial on Building a REST API Using Python and Flask

Posted by


In this tutorial, we will explore how to build a Flask REST API using Python. Flask is a lightweight web framework that is easy to use and can be scaled to build complex web applications.

Step 1: Install Flask
To get started, make sure you have Python installed on your machine. You can download and install Python from the official website. Once you have Python installed, you can install Flask using pip, the Python package installer. Open a terminal or command prompt and run the following command:

pip install Flask

Step 2: Create a new Flask project
Now that Flask is installed, we can create a new Flask project. Create a new directory for your project and navigate into it. Then create a new Python file, for example, app.py, and open it in your favorite code editor.

from flask import Flask

app = Flask(__name__)

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

This is a simple Flask application that creates a Flask instance and starts the development server when the script is executed. To start the app, run the following command in your terminal:

python app.py

You should see output indicating that the Flask development server is running. Open a web browser and navigate to http://127.0.0.1:5000/. You should see a message saying "Hello World!" indicating that the Flask app is running successfully.

Step 3: Create a REST API endpoint
Now that we have a basic Flask application set up, let’s create a REST API endpoint that returns some data. Modify the app.py file to include a new route that returns a JSON response.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/data', methods=['GET'])
def get_data():
    data = {'message': 'Hello, welcome to the Flask REST API tutorial!'}
    return jsonify(data)

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

In this code snippet, we have added a new route /api/data that returns a JSON response with a welcome message. The jsonify function is used to convert the data dictionary to a JSON response.

Restart the Flask application by stopping the development server and running python app.py again. Open a web browser and navigate to http://127.0.0.1:5000/api/data. You should see the JSON response with the welcome message.

Step 4: Handle HTTP methods
In a REST API, you typically want to handle different HTTP methods such as GET, POST, PUT, and DELETE. Let’s modify the existing endpoint to handle GET and POST requests.

from flask import Flask, request, jsonify

app = Flask(__name__)

data = []

@app.route('/api/data', methods=['GET', 'POST'])
def handle_data():
    if request.method == 'GET':
        return jsonify(data)
    elif request.method == 'POST':
        new_data = request.json
        data.append(new_data)
        return jsonify(new_data)

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

In this code snippet, we have modified the /api/data route to handle both GET and POST requests. When a GET request is made, the API returns the current data. When a POST request is made, the API adds the new data to the data list and returns the new data.

Step 5: Test the REST API
To test the REST API endpoints, you can use a tool like Postman or cURL. Send a GET request to http://127.0.0.1:5000/api/data to retrieve the current data. Send a POST request with a JSON payload to http://127.0.0.1:5000/api/data to add new data to the API.

Congratulations! You have successfully built a Flask REST API using Python. This tutorial covered the basics of setting up a Flask project, creating REST API endpoints, handling HTTP methods, and testing the API. You can now expand on this knowledge to build more complex APIs with authentication, database integration, and error handling. Have fun building REST APIs with Flask!

0 0 votes
Article Rating
34 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@TechWithTim
3 months ago

Hope you all enjoyed! Realize I forgot to show how to delete from database, you can look here to find that information! https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/

@athiramariaphilip8399
3 months ago

This helped me a lot to clear my concepts on flask REST API. Thank you for simplified video on this topic.

@younes9191
3 months ago

Thank you

@iamno1special
3 months ago

UPDATE – In order to create the sqlalchemy database replace db.create_all() with:

with app.app_context():
db.create_all()

@spuckhafte
3 months ago

reZourZe

@doomstarks182
3 months ago

Re zorce

@chisomedoka5651
3 months ago

why didn't Tim use decorators for routes

@domukelis
3 months ago

What the fuck am i doing

@BloodswordFW
3 months ago

re- S̲ -ource please <3

@raffaelebarbato8211
3 months ago

thanks for the video, it was all clear and so useful 🙂

@not_amanullah
3 months ago

This is helpful ❤

@not_amanullah
3 months ago

Thanks ❤

@user-yn7cd2bl2i
3 months ago

Thanks man, you covered everyting I need to know to start my college project

@milanmgeorfin529
3 months ago

Which app this is used and in windows or in ubuntu

@vaclavhanzl8193
3 months ago

Hi, is this video actually outdated??? Been trying to go according to the tutorial but some things just does not work for me

@tamalroy1486
3 months ago

You didn't change the delete function after adding the sql db

@apoorvtewari1426
3 months ago

Thanks Tim for explaining it so well that no other resource was required to grasp the basics of FLASK

@DarasaDijito
3 months ago

Man you are the best,your video has helped me shape the world of Api in Education,i will send you an invitation to Tanzania so you could come

@RedrumComedy
3 months ago

you're the goat bro

@gkozgkeiros5750
3 months ago

is there any difference if i wanted to add mysql?(im using xampp)