How to Create a RESTful API with Flask: A Practical Guide
Flask is a lightweight Python web framework that makes building RESTful APIs straightforward. With minimal boilerplate, you can design endpoints that handle CRUD operations and return JSON. This tutorial walks you through the core steps to create a simple API.
Start by installing Flask in a virtual environment: pip install flask. Create a file like app.py and import Flask. Set up the app instance and run it with app.run() to verify everything works.
1. Define Resource Endpoints
Use Flask route decorators to map URLs to functions. For a books API, define an endpoint like /api/books. Each function corresponds to a resource, and you can store data in a list or dictionary for simplicity.
2. Handle HTTP Methods
Flask routes default to GET. To support POST, PUT, or DELETE, pass the methods parameter: @app.route('/api/books', methods=['GET', 'POST']). Inside the function, check request.method and execute the appropriate logic—create, read, update, or delete.
3. Return JSON Responses
Use Flask’s jsonify function to return JSON objects. For a list of books, return jsonify(books). For errors, set the response status code: jsonify({'error': 'Not found'}), 404. This ensures your API adheres to REST conventions.
4. Test with curl or Postman
Run your Flask app and send requests using curl or Postman. For example, curl http://127.0.0.1:5000/api/books returns the list. Test POST by sending JSON data with the Content-Type: application/json header.
Creating a RESTful API with Flask is fast and flexible. For more complex projects, consider using the Flask-RESTful extension, but the core patterns above give you full control. Start small, test often, and your API will be production-ready in no time.