How to Create REST API in Flask: Simple Guide with Example
To create a REST API in Flask, define routes using the
@app.route decorator and handle HTTP methods like GET and POST in your functions. Use Flask to create the app and return JSON responses with jsonify.Syntax
In Flask, you create REST API endpoints by defining routes with the @app.route decorator. You specify the URL path and allowed HTTP methods. Inside the function, you handle the request and return a response, often in JSON format.
- @app.route('/path', methods=['GET', 'POST']): Defines the URL and HTTP methods.
- def function_name(): The function that runs when the route is accessed.
- return jsonify(data): Sends JSON response back to the client.
python
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/resource', methods=['GET', 'POST']) def resource(): if request.method == 'GET': return jsonify({'message': 'This is a GET request'}) elif request.method == 'POST': data = request.get_json() return jsonify({'you_sent': data}), 201 if __name__ == '__main__': app.run(debug=True)
Example
This example shows a simple Flask REST API with one endpoint /items. It supports GET to list items and POST to add a new item. The API returns JSON responses.
python
from flask import Flask, jsonify, request app = Flask(__name__) items = [] @app.route('/items', methods=['GET', 'POST']) def items_api(): if request.method == 'GET': return jsonify({'items': items}) elif request.method == 'POST': item = request.get_json().get('item') if item: items.append(item) return jsonify({'message': 'Item added', 'items': items}), 201 else: return jsonify({'error': 'No item provided'}), 400 if __name__ == '__main__': app.run(debug=True)
Output
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
Common Pitfalls
Common mistakes when creating REST APIs in Flask include:
- Not specifying HTTP methods in
@app.route, so only GET works by default. - Forgetting to parse JSON from
request.get_json()for POST requests. - Returning plain strings instead of JSON responses, which can confuse clients.
- Not setting proper HTTP status codes like 201 for resource creation or 400 for bad requests.
Example of a wrong and right way:
python
from flask import Flask, jsonify, request app = Flask(__name__) # Wrong: No methods specified, only GET allowed @app.route('/wrong') def wrong(): return 'This only supports GET' # Right: Methods specified and JSON response @app.route('/right', methods=['POST']) def right(): data = request.get_json() if not data: return jsonify({'error': 'Missing JSON'}), 400 return jsonify({'received': data}), 200 if __name__ == '__main__': app.run(debug=True)
Quick Reference
Tips for creating REST APIs in Flask:
- Always specify
methods=['GET', 'POST', ...]in routes. - Use
request.get_json()to get JSON data from clients. - Return responses with
jsonify()for proper JSON formatting. - Set HTTP status codes to indicate success or errors.
- Run Flask with
debug=Trueduring development for helpful error messages.
Key Takeaways
Use @app.route with methods to define REST API endpoints in Flask.
Handle JSON input with request.get_json() and respond with jsonify().
Always set appropriate HTTP status codes for clarity.
Test your API endpoints with tools like curl or Postman.
Run Flask in debug mode during development for easier troubleshooting.