Home > Backend Development > Python Tutorial > How to build a RESTful API using Flask

How to build a RESTful API using Flask

王林
Release: 2023-06-17 18:31:12
Original
1067 people have browsed it

In today's software development field, RESTful API has become a core component of many applications, which can provide reliable, decoupled, and easy-to-maintain services. Flask is a lightweight Python web framework that provides a flexible way to build web applications as well as RESTful APIs. In this article, we will introduce how to use Flask to build a RESTful API.

  1. Installing Flask

First, you need to make sure that Python and pip are installed. Open a terminal or command prompt on your system and enter the following command to install Flask:

pip install Flask
Copy after login
  1. Create project folder

In this example, we create a project folder named It is the project folder of "flask-restful". Enter the following command in the terminal to create the folder:

mkdir flask-restful
Copy after login
  1. Create a virtual environment

It is recommended to use a virtual environment to avoid installing Flask globally on the system, this can Help us develop multiple projects on the same computer. Enter the following command in the terminal to create the virtual environment:

python3 -m venv env
Copy after login
  1. Activate the virtual environment

To activate the virtual environment in the terminal, enter the following command:

For Mac/Linux:

source env/bin/activate
Copy after login

For Windows:

envScriptsctivate
Copy after login
  1. Add necessary dependencies

In a Flask application, you need to use flask_restful library and other libraries to safely perform RESTful API requests. These dependencies can be installed using the pip command in a virtual environment:

pip install flask_restful
pip install flask_cors
Copy after login
  1. Creating the application master file

Before creating our RESTful API, we need to create a Application master file. Create a file called "app.py" in the project folder and add the following code:

from flask import Flask
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

users = [
    {
        "name": "Alice",
        "age": 22,
        "occupation": "Software Engineer"
    },
    {
        "name": "Bob",
        "age": 26,
        "occupation": "Data Analyst"
    },
    {
        "name": "Charlie",
        "age": 33,
        "occupation": "UI/UX Designer"
    }
]

class User(Resource):
    def get(self, name):
        for user in users:
            if(name == user["name"]):
                return user, 200
        return "User not found", 404

api.add_resource(User, "/user/<string:name>")

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

The above code creates a Flask application instance called "app" and an instance called "api "flask_restful object. It also defines some data to store user information. In this application, we also define a class called "User", which inherits from flask_restful's "Resource" class. The User class defines two methods - get and post. We only implemented the get method, which is used to obtain user data with a specified name. Finally, bind the User class to the /user/ endpoint on the api.

  1. Run the application

In a terminal or command prompt, enter the following command to start the application:

python app.py
Copy after login

Then, visit http:// /localhost:5000/user/Alice (or the name of other users) can obtain the user data.

  1. Add CORS support

CORS stands for cross-origin resource sharing. When using RESTful APIs, CORS support can be used in the development environment to avoid cross-domain resource issues. In our application, we added CORS support using the flask_cors library. To add CORS support, simply add the following code to your application main file:

from flask_cors import CORS

app = Flask(__name__)
api = Api(app)
CORS(app)
Copy after login

This code is added after the application instance and api definition. It binds CORS middleware to the application instance.

Conclusion

In this article, we introduced how to build a RESTful API using Flask. We start by installing Flask, then create the project folder, virtual environment, add dependencies, and create the main application file. We also learned how to add CORS support to help solve cross-origin resource request issues. Now you can easily build RESTful API services using Flask.

The above is the detailed content of How to build a RESTful API using Flask. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template