0
0
Flaskframework~5 mins

HTTP status codes for APIs in Flask

Choose your learning style9 modes available
Introduction

HTTP status codes tell the client if the API request worked or if there was a problem. They help both the server and client understand what happened.

When sending a success response after creating a new resource
When the client sends bad data that the server cannot process
When a requested resource is not found on the server
When the client is not authorized to access a resource
When the server encounters an unexpected error
Syntax
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/example')
def example():
    data = {'message': 'Success!'}
    return jsonify(data), 200

The status code is returned as the second value in the return statement.

Common status codes include 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found), 500 (Internal Server Error).

Examples
Returns a 201 status code to indicate a new resource was created successfully.
Flask
return jsonify({'message': 'Created'}), 201
Returns a 400 status code when the client sends invalid data.
Flask
return jsonify({'error': 'Bad request'}), 400
Returns a 404 status code when the requested resource does not exist.
Flask
return jsonify({'error': 'Not found'}), 404
Returns a 500 status code when the server has an unexpected error.
Flask
return jsonify({'error': 'Server error'}), 500
Sample Program

This Flask app has two routes: one to get an item by ID and one to create a new item.

It uses HTTP status codes to tell the client if the request was successful or if there was an error like not found or bad request.

Flask
from flask import Flask, jsonify, request

app = Flask(__name__)

items = {'1': 'apple', '2': 'banana'}

@app.route('/items/<item_id>', methods=['GET'])
def get_item(item_id):
    if item_id in items:
        return jsonify({'item': items[item_id]}), 200
    else:
        return jsonify({'error': 'Item not found'}), 404

@app.route('/items', methods=['POST'])
def create_item():
    data = request.get_json()
    if not data or 'id' not in data or 'name' not in data:
        return jsonify({'error': 'Bad request, id and name required'}), 400
    if data['id'] in items:
        return jsonify({'error': 'Item already exists'}), 400
    items[data['id']] = data['name']
    return jsonify({'message': 'Item created'}), 201

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

Always return the correct status code to help clients handle responses properly.

Use 2xx codes for success, 4xx for client errors, and 5xx for server errors.

Flask lets you return status codes easily by returning a tuple with the response and code.

Summary

HTTP status codes communicate the result of an API request.

Use Flask's return syntax to send both data and status codes.

Common codes: 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found), 500 (Internal Server Error).