Building a RESTful API with Flask in Python

Building a RESTful API with Flask in Python

Introduction: In today's interconnected world, APIs (Application Programming Interfaces) are the backbone of web applications, mobile apps, and even IoT devices. RESTful APIs, adhering to the REST architectural style, offer a standardized and efficient way to communicate between different systems. This tutorial will guide you through building a simple yet powerful RESTful API using Flask, a lightweight and flexible Python web framework. We'll create an API for managing a collection of books, demonstrating CRUD (Create, Read, Update, Delete) operations.

Requirements

  • Python 3.7+
  • Flask
  • Postman (or any API testing tool)

Setting Up

First, create a virtual environment and install Flask:

python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install Flask

Project Structure

Create a file named `app.py`:

Code: app.py


from flask import Flask, jsonify, request

app = Flask(__name__)

books = [
    {'id': 0, 'title': 'The Hitchhiker\'s Guide to the Galaxy', 'author': 'Douglas Adams'},
        {'id': 1, 'title': 'Pride and Prejudice', 'author': 'Jane Austen'}
        ]
        
        
        @app.route('/books', methods=['GET'])
        def get_books():
            return jsonify({'books': books})
            
            
            @app.route('/books/', methods=['GET'])
            def get_book(book_id):
                book = [book for book in books if book['id'] == book_id]
                    if len(book) == 0:
                            return jsonify({'error': 'Book not found'}), 404
                                return jsonify({'book': book[0]})
                                
                                
                                
                                @app.route('/books', methods=['POST'])
                                def create_book():
                                  new_book = request.get_json()
                                    new_book['id'] = len(books) # auto assign IDs
                                      books.append(new_book)
                                        return jsonify({'message':'Book created','book': new_book}), 201
                                        
                                        @app.route('/books/',methods=['PUT'])
                                        def update_book(book_id):
                                            updated_book = request.get_json()
                                                for i,book in enumerate(books):
                                                        if book['id'] == book_id:
                                                                    books[i] = updated_book  # Ideally, only update specific fields
                                                                                books[i]['id'] = book_id # Ensure ID remains unchanged
                                                                                            return jsonify({'message': 'Book updated', 'book': books[i]})
                                                                                                return jsonify({'error':'Book not found'}), 404
                                                                                                
                                                                                                
                                                                                                
                                                                                                @app.route('/books/',methods=['DELETE'])
                                                                                                def delete_book(book_id):
                                                                                                    for i,book in enumerate(books):
                                                                                                            if book['id'] == book_id:
                                                                                                                        del books[i]
                                                                                                                                    return jsonify({'message':'Book deleted'})
                                                                                                                                        return jsonify({'error':'Book not found'}), 404
                                                                                                                                        
                                                                                                                                        
                                                                                                                                        
                                                                                                                                        if __name__ == '__main__':
                                                                                                                                            app.run(debug=True)
                                                                                                                                            

Code Breakdown

  • We initialize a list books to store our book data.
  • @app.route decorators define the API endpoints and accepted HTTP methods.
  • jsonify converts Python dictionaries to JSON responses.
  • We use different HTTP methods (GET, POST, PUT, DELETE) for different CRUD operations.
  • Error handling is implemented for scenarios like book not found.

Running the API

python app.py
                                                                                                                                                                
This starts the Flask development server. You can then use Postman to interact with your API at http://127.0.0.1:5000/books.

Testing with Postman

* **GET /books:** Retrieve all books. * **GET /books/0:** Retrieve book with ID 0. * **POST /books:** Create a new book (send JSON data in the request body). * **PUT /books/0:** Update book with ID 0 (send JSON data in the request body). * **DELETE /books/0:** Delete book with ID 0.

Conclusion

This tutorial provided a practical introduction to building a RESTful API with Flask. You've learned how to handle different HTTP requests, manage data, and return JSON responses. From here, you can explore more advanced Flask features like database integration, authentication, and API documentation to create more robust and scalable APIs. Experiment with different endpoints and data structures to solidify your understanding. Happy coding!

Comments