Home > Backend Development > Python Tutorial > Python Server Programming: Building a RESTful API with Flask

Python Server Programming: Building a RESTful API with Flask

王林
Release: 2023-06-18 09:50:27
Original
1239 people have browsed it

Python server programming: Use Flask to build RESTful API

Python has always been one of the popular languages ​​​​for developing web applications. It is an easy-to-use, feature-rich, flexible and efficient language. Using RESTful APIs in web applications has become a very popular trend. Using the Flask framework in Python is a great option for web programming and building RESTful APIs. In this article, we will take an in-depth look at how to build a RESTful API using the Flask framework.

First, we need to understand RESTful API. RESTful API is an API design style based on the HTTP/HTTPS protocol, which uses a unified interface to transmit data between the client and the server. RESTful API has the following characteristics:

  • Stateless
  • Scalability
  • Resource Identifier
  • Based on HTTP protocol

Next, we will use the Flask framework to build a RESTful API. Flask is a lightweight web framework written in Python that is easy to learn and use. The Flask framework has a rich expansion library that can meet various needs. The benefits of using the Flask framework include:

  • Simple code, easy to maintain
  • High flexibility, supports multiple types of projects
  • Lightweight, high performance
  • It is very convenient to write RESTful API

First you need to install the Flask framework, which can be installed through the following command:

pip install flask
Copy after login

Next, we start to use the Flask framework to build RESTful API. First, we need to write a Hello World program to verify that the Flask framework has been installed correctly. We can define a Flask application and define a route '/' to handle requests. The code is as follows:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def helloWorld():
    return 'Hello, World!'

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

Enter 'http://localhost:5000/' in the browser, 'Hello, World!' will be displayed.

Next, we will introduce how to use the Flask framework to build a RESTful API.

First, we define a Flask application and create a route to respond to GET requests. The code is as follows:

from flask import Flask, jsonify

app = Flask(__name__)
books = [
    {
        'id': 1,
        'title': 'The Great Gatsby',
        'author': 'F. Scott Fitzgerald',
        'published': '1925'
    },
    {
        'id': 2,
        'title': 'To Kill a Mockingbird',
        'author': 'Harper Lee',
        'published': '1960'
    }
]

@app.route('/books/<int:id>', methods=['GET'])
def get_book(id):
    for book in books:
        if book['id'] == id:
            return jsonify(book)
    return jsonify({'error': 'Book not found'})

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

In the above code, we define a books list, containing two dictionaries, each A dictionary represents a book. A route '/books/' is defined, passing an integer id parameter using ''. In the function, we traverse to find books by id, and if found, return the bookstore details, otherwise return an error message.

Enter 'http://localhost:5000/books/1' in the browser, and detailed information about a book named 'The Great Gatsby' will be returned.

Next, we will extend the above code to support other methods of HTTP requests.

@app.route('/books', methods=['GET', 'POST'])
def handle_books():
    if request.method == 'GET':
        return jsonify(books)
    if request.method == 'POST':
        new_book = {
            'id': len(books) + 1,
            'title': request.form['title'],
            'author': request.form['author'],
            'published': request.form['published']
        }
        books.append(new_book)
        return jsonify(new_book)
Copy after login

In the above code, we defined a new route '/books' to handle HTTP GET and POST requests. In a GET request, we return the entire books list. In the POST request, we add the new book to the books list.

Next, we will implement the DELETE and PUT methods.

@app.route('/books/<int:id>', methods=['GET', 'PUT', 'DELETE'])
def handle_book(id):
    if request.method == 'GET':
        for book in books:
            if book['id'] == id:
                return jsonify(book)
        return jsonify({'error': 'Book not found'})

    if request.method == 'PUT':
        for book in books:
            if book['id'] == id:
                book['title'] = request.form['title']
                book['author'] = request.form['author']
                book['published'] = request.form['published']
                return jsonify(book)
        return jsonify({'error': 'Book not found'})

    if request.method == 'DELETE':
        for book in books:
            if book['id'] == id:
                books.remove(book)
                return jsonify({'message': 'Book deleted'})
        return jsonify({'error': 'Book not found'})
Copy after login

In the above code, we extend the processing of route '/books/'. In the GET request, we look for the book associated with id. In the PUT request, we update the book associated with id. In DELETE request, we delete the book related to id.

So far, we have learned how to use Flask to build a RESTful API. We've seen how to use Flask to define resources and expose them to HTTP requests. We also learned how to use various REST practices to implement GET, POST, PUT, and DELETE operations. Additionally, we saw how to use Flask responses to return data.

In short, the Flask framework is an ideal choice for implementing RESTful APIs. It is fast, simple, easy to learn and use, and supports the Python language. In this article, we show how to build a RESTful API using Flask. So easy, you can now start creating your own RESTful API to serve your application.

The above is the detailed content of Python Server Programming: Building a RESTful API with 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