Flask-Restful framework practice
FLASK-RESTFUL framework practice
Overview:
Flask-Restful is an open source expansion based on the Flask framework and is used to build a RESTFUL API.It provides a simple and flexible method to create high -efficiency and scalable web services.This article will introduce how to use the Flask-Restful framework to achieve a simple API and give a complete program code and related configuration.
Installation and configuration FLASK-RESTFUL:
First, make sure that Python and PIP have been installed.Then use the following commands to install Flask and Flask-Restful extensions:
pip install flask flask-restful
Create FLASK-RESTFUL Application:
Before starting to write code, you need to create a new Flask application.Create a file called `app.py` under the root directory of the project, and add the following code:
python
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'Hello': 'World'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)
In the above code, we introduced the necessary modules and created a FLASK application and an API instance.Next, we define a resource class called `HelloWorld`, which contains a` Get` method, which will return a JSON response.Then, we use the `API.ADD_Resource ()` method to bind the resource class and the URL path together.Finally, we use the `app.run () method to run the application.
Run application:
To run the application, you can navigate to the root directory of the project in the console and execute the following command:
python app.py
If everything goes well, you will see the output similar to the following in the console:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Now, you can open the `http://127.0.0.0.0.1: 5000 /`, or use any API test tool to send a GET request.You will receive the following response:
{"Hello": "World"}
Summarize:
This article introduces how to use the Flask-Restful framework to achieve a simple API.First, we installed Flask and Flask-Restful extensions.Then, we created a Flask application and defined a resource class to handle the GET request and return the JSON response.Finally, we run the application and test it through the browser or API test tool.Through this simple example, you can start using the Flask-RESTFUL framework to build a more complex RESTFUL Web service.