Home >Backend Development >Python Tutorial >Flask-RESTful: Building RESTful APIs using Python
Flask-RESTful: Use Python to build RESTful API
With the rise of modern Internet services, RESTful API has become the standard for communication protocols. To develop high-quality RESTful APIs, Python has an efficient framework, Flask-RESTful. This article will introduce what Flask-RESTful is and how to build a RESTful API using Python.
Part 1: Understanding RESTful API
REST (Representational State Transfer) is a web service architectural style based on the HTTP protocol. It allows the client to request access and obtain resources, and allows the server to return The requested resource. API (Application Programming Interface) is a communication protocol between programs and systems, which allows different applications to communicate with each other through defined interfaces to complete specific tasks. A RESTful API consists of two parts: resources (URIs) and behaviors (HTTP methods).
Resources are the core of RESTful API, which is the representation of internal data. A URI (Uniform Resource Identifier) specifies the location of each resource, and each resource has a unique URI. Behavior, on the other hand, specifies how a resource is accessed and manipulated. RESTful API uses HTTP methods to define these operations, for example, the GET method is used to retrieve resources, the POST method is used to create resources, the PUT method is used to update resources, and the DELETE method is used to delete resources.
Part 2: Introduction to Flask-RESTful
Flask-RESTful is an extension module of Flask and a Python RESTful framework. It provides simplified methods and tools for building RESTful APIs. The advantages of Flask-RESTful are as follows:
1. Easy to use
Flask-RESTful is a lightweight framework based on the Flask framework. It provides a simple set of tools that can help developers quickly build RESTful APIs without writing a lot of repetitive code.
2. Rapid development
Due to some simplified methods, such as request parameter parsing and route creation, API development time can be significantly reduced.
3. Provides support for extension and customization
Flask-RESTful provides flexible extension and customization points, and developers can extend its functions as needed.
4. The documentation is very detailed
Flask-RESTful's documentation is very detailed and easy to learn and use.
Part 3: How to use Flask-RESTful
Next, we will introduce how to use Flask-RESTful to build a RESTful API. We will create a simple API for managing movie data. This API will allow the client to perform the following operations:
1. List all movies
2. Get detailed information about a movie
3. Add new movies
4. Update movie information
5. Delete movie records
First, install and configure Flask-RESTful and create a Python virtual environment. Install Flask-RESTful using the following command (make sure pip is installed):
pip install flask-restful
Next, create an app.py file. This file must import the required modules and libraries. This file will define and implement the Flask application.
from flask import Flask, request from flask_restful import Resource, Api, reqparse app = Flask(__name__) api = Api(app)
Here we introduce Flask and Flask-RESTful libraries and modules. Next, let's define some dummy data.
movies = [ { 'id': 1, 'title': 'The Shawshank Redemption', 'director': 'Frank Darabont', 'year_released': 1994}, { 'id': 2, 'title': 'Forrest Gump', 'director': 'Robert Zemeckis', 'year_released': 1994}, { 'id': 3, 'title': 'The Matrix', 'director': 'The Wachowski Brothers', 'year_released': 1999}, { 'id': 4, 'title': 'Léon: The Professional', 'director': 'Luc Besson', 'year_released': 1994}, { 'id': 5, 'title': 'The Dark Knight', 'director': 'Christopher Nolan', 'year_released': 2008}, { 'id': 6, 'title': 'Interstellar', 'director': 'Christopher Nolan', 'year_released': 2014}, { 'id': 7, 'title': 'Inception', 'director': 'Christopher Nolan', 'year_released': 2010}, { 'id': 8, 'title': 'The Lord of the Rings: The Fellowship of the Ring', 'director': 'Peter Jackson', 'year_released': 2001}, { 'id': 9, 'title': 'Gladiator', 'director': 'Ridley Scott', 'year_released': 2000}, { 'id': 10, 'title': 'The Godfather', 'director': 'Francis Ford Coppola', 'year_released': 1972} ]
Now, create 5 different resources to handle 5 different HTTP requests: GET, POST, PUT, DELETE.
class MovieList(Resource): def get(self): return { 'movies': movies } def post(self): parser = reqparse.RequestParser() parser.add_argument('title', type=str, required=True, help='Title is required.') parser.add_argument('director', type=str, required=True, help='Director is required.') parser.add_argument('year_released', type=int, required=True, help='Year must be a number.') args = parser.parse_args() movie = { 'id': len(movies) + 1, 'title': args['title'], 'director': args['director'], 'year_released': args['year_released'] } movies.append(movie) return movie, 201 class Movie(Resource): def get(self, movie_id): movie = next(filter(lambda x:x['id']==movie_id, movies), None) return {'movie': movie}, 200 if movie else 404 def put(self, movie_id): parser = reqparse.RequestParser() parser.add_argument('title', type=str, required=True, help='Title is required.') parser.add_argument('director', type=str, required=True, help='Director is required.') parser.add_argument('year_released', type=int, required=True, help='Year must be a number.') args = parser.parse_args() movie = next(filter(lambda x:x['id']==movie_id, movies), None) if movie is None: movie = {'id': movie_id, 'title': args['title'], 'director': args['director'], 'year_released': args['year_released']} movies.append(movie) else: movie.update(args) return movie def delete(self, movie_id): global movies movies = list(filter(lambda x:x['id']!=movie_id, movies)) return {'message': 'Movie deleted.'}, 200
These resources are mapped to paths associated with the URL.
api.add_resource(MovieList, '/movies') api.add_resource(Movie, '/movies/<int:movie_id>')
Now, start the Flask application and check the localhost ( http://127.0.0.1:5000/movies ), we can see the API list we just created:
{ "movies": [ { "director": "Frank Darabont", "id": 1, "title": "The Shawshank Redemption", "year_released": 1994 }, ... ] }
Now, We can add a new movie using POST method.
import requests url = 'http://localhost:5000/movies' data = {"title": "The Green Mile", "director": "Frank Darabont", "year_released": "1999"} res = requests.post(url, data=data)
The complete request and response are as follows:
<Response [201]> {'id': 11, 'title': 'The Green Mile', 'director': 'Frank Darabont', 'year_released': 1999}
We can also use the PUT method to update movie information.
url = 'http://localhost:5000/movies/11' data = {"title": "The Green Mile", "director": "Frank Darabont", "year_released": "1999"} res = requests.put(url, data=data)
Finally, let’s delete a movie.
url = 'http://localhost:5000/movies/11' res = requests.delete(url)
We created a simple RESTful API using the Flask-RESTful framework to make it easy to develop and maintain. RESTful API is an essential component for developing web applications. It allows clients to access and update resources and emphasizes URI and HTTP methods. Using Flask-RESTful at the same time can speed up the team's development and simplify the code.
The above is the detailed content of Flask-RESTful: Building RESTful APIs using Python. For more information, please follow other related articles on the PHP Chinese website!