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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
