Building a Python REST API with Flask: A Comprehensive Guide

Building a Python REST API with Flask: A Comprehensive Guide

Creating a REST API with Python is a common task for developers who want to build scalable web applications. Python’s simplicity, along with powerful frameworks like Flask, makes it easy to create RESTful services that can be consumed by various clients (web, mobile, etc.). In this article, we will walk through how to build a simple REST API using Flask, a popular lightweight web framework in Python.

Why Flask?

Flask is a micro-framework for Python that provides the essentials for web development without enforcing too many constraints. It’s minimalistic, making it ideal for building APIs where you only need the core functionality.

Setup

First, let’s start by setting up our environment and installing Flask:

  1. Install Python (version 3.7+ recommended).
  2. Create a virtual environment (optional but recommended):

python3 -m venv venv
source venv/bin/activate  # For Mac/Linux
venv\Scripts\activate     # For Windows        

  1. Install Flask:

pip install flask        

Building the API

Now, let’s create a simple REST API that allows us to manage a list of books. We’ll provide endpoints to:

  • Retrieve all books.
  • Retrieve a specific book by ID.
  • Add a new book.
  • Update an existing book.
  • Delete a book.

Step 1: Basic Flask Application

Start by setting up a basic Flask application:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def hello():
    return "Welcome to the Book API"

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

If you run this (python app.py), it will start a local web server on https://127.0.0.1:5000. When you visit that URL, you should see "Welcome to the Book API."

Step 2: Define a Book Resource

We will define a simple in-memory list of books, where each book has an id, title, and author.

books = [
    {"id": 1, "title": "1984", "author": "George Orwell"},
    {"id": 2, "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"},
    {"id": 3, "title": "To Kill a Mockingbird", "author": "Harper Lee"},
]        

Step 3: Create REST Endpoints

Now, let’s create RESTful endpoints to manage the books. We’ll use GET, POST, PUT, and DELETE HTTP methods.

1. Retrieve All Books

To retrieve all books, we’ll use the GET method on the /books endpoint.

@app.route('/books', methods=['GET'])
def get_books():
    return jsonify(books), 200        

2. Retrieve a Single Book by ID

To fetch a single book by its ID:

@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
    book = next((book for book in books if book['id'] == book_id), None)
    if book is None:
        return jsonify({"message": "Book not found"}), 404
    return jsonify(book), 200        

3. Add a New Book

We’ll use the POST method to add a new book. The book details will be sent as JSON in the request body.

from flask import request

@app.route('/books', methods=['POST'])
def add_book():
    new_book = request.get_json()
    new_book['id'] = len(books) + 1
    books.append(new_book)
    return jsonify(new_book), 201        

4. Update an Existing Book

To update a book’s information, we’ll use the PUT method and send the updated data as JSON:

@app.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
    book = next((book for book in books if book['id'] == book_id), None)
    if book is None:
        return jsonify({"message": "Book not found"}), 404
    
    updated_data = request.get_json()
    book.update(updated_data)
    return jsonify(book), 200        

5. Delete a Book

To delete a book by its ID, we’ll use the DELETE method:

@app.route('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
    global books
    books = [book for book in books if book['id'] != book_id]
    return jsonify({"message": "Book deleted"}), 200        

Testing the API

To test the API, you can use tools like Postman or curl.

For example, to fetch all books:

curl https://127.0.0.1:5000/books        

To add a new book:

curl -X POST -H "Content-Type: application/json" -d '{"title": "The Catcher in the Rye", "author": "J.D. Salinger"}' https://127.0.0.1:5000/books        

Adding Error Handling

Good APIs handle errors gracefully. Let’s add basic error handling for invalid requests:

@app.errorhandler(404)
def not_found(error):
    return jsonify({"message": "Resource not found"}), 404

@app.errorhandler(400)
def bad_request(error):
    return jsonify({"message": "Bad request"}), 400        

Conclusion

In this article, we covered how to build a simple REST API in Python using Flask. We handled basic CRUD operations for a list of books and learned how to define routes for different HTTP methods. Flask’s flexibility and simplicity make it a great choice for building APIs, whether for small or large applications. You can extend this example by adding a database, authentication, or more complex business logic.

Leandro Veiga

Senior Software Engineer | Full Stack Developer | C# | .NET | .NET Core | React | Amazon Web Service (AWS)

5 个月

Interesting

Elieudo Maia

Fullstack Software Engineer | Node.js | React.js | Javascript & Typescript | Go Developer

5 个月

Great content. Thanks for sharing!

Idalio Pessoa

Senior Ux Designer | Product Designer | UX/UI Designer | UI/UX Designer | Figma | Design System |

5 个月

Kudos to Alexandre Pereira for sharing a comprehensive guide on building a REST API with Flask. As a UX designer, I appreciate how he structured the content for an easy-to-follow learning experience. The use of a simple book list analogy helps illustrate complex concepts effectively.

Lucas Wolff

.NET Developer | C# | TDD | Angular | Azure | SQL

5 个月

Thanks for sharing this article

Thiago Nunes Monteiro

Senior Mobile Developer | Android Software Engineer | Jetpack Compose | GraphQL | Kotlin | Java | React Native

5 个月

Great article Alexandre Pereira, Thanks for sharing!

要查看或添加评论,请登录

Alexandre Pereira的更多文章

社区洞察

其他会员也浏览了