Browse Courses

Error Handling

This document explains HTTP status codes, error handling in Flask, and how to return appropriate error responses from API endpoints, including application-level error handlers.

This document covers HTTP status codes, error handling in Flask, and best practices for returning error responses from API endpoints. It explains status code categories, custom error responses, and application-level error handlers for robust API design.


Understanding HTTP Status Codes

Every HTTP response includes a three-digit status code that indicates the result of the request. Status codes are grouped into categories:

Code RangeCategoryDescription
100–199InformationalRequest received, continuing process
200–299SuccessRequest received and processed successfully
300–399RedirectionFurther action needed to complete request
400–499Client ErrorError in the request from the client
500–599Server ErrorError on the server side

Common codes include:

CodeMeaning
200OK
201Created
202Accepted
204No Content
400Bad Request
401Unauthorized
403Forbidden
404Not Found
405Method Not Allowed
422Unprocessable Entity
500Internal Server Error

Returning Status Codes in Flask

Flask returns a 200 OK status by default when a route returns a response. To return a different status code, provide it as a tuple or use the make_response method.

 1from flask import Flask, make_response
 2
 3app = Flask(__name__)
 4
 5@app.route('/')
 6def home():
 7    return '<h1>My First Application in Action</h1>', 200
 8
 9@app.route('/custom')
10def custom():
11    response = make_response('<h1>Custom Response</h1>', 200)
12    return response

Example: Handling API Errors

When building APIs, return appropriate status codes for different outcomes:

 1@app.route('/search')
 2def search_response():
 3    query = request.args.get('q')
 4    if not query:
 5        return {'message': 'Input parameter missing'}, 422
 6    result = fetch_from_database(query)
 7    if result:
 8        return result, 200
 9    else:
10        return {'message': 'Resource not found'}, 404

This example returns 422 if a required parameter is missing, 200 if the resource is found, and 404 if not found.


Application-Level Error Handlers in Flask

Flask allows defining custom error handlers for specific status codes at the application level:

1@app.errorhandler(404)
2def not_found(error):
3    return {'message': 'API not found'}, 404
4
5@app.errorhandler(500)
6def server_error(error):
7    return {'message': 'Something went wrong on the server'}, 500

These handlers return custom messages and status codes for 404 and 500 errors.


Conclusion

HTTP status codes communicate the result of API requests. Flask provides default and custom ways to return status codes and error messages, including application-level error handlers for robust API design.


FAQ

  1. To identify the client
  2. To indicate the result of the request
  3. To store user data
  4. To encrypt the response
(2) HTTP status codes indicate the result of the request, such as success, client error, or server error.

Flask will return a 200 OK status code by default.

The make_response method allows you to explicitly set the status code in a Flask response.

CodeMeaning
A. 2001. Unauthorized
B. 2012. Created
C. 4013. OK
D. 4044. Not Found
A-3, B-2, C-1, D-4.

  1. Flask always returns a 200 status code
  2. Custom error handlers can be defined for specific status codes
  3. Status codes can be returned as part of a tuple
  4. Application-level error handlers can return custom messages
(1) Flask does not always return a 200 status code; custom codes can be returned.

Flask allows defining application-level error handlers for specific status codes.

True. Flask supports custom error handlers for status codes like 404 and 500.

The presence of required parameters should be checked first, returning an appropriate status code if missing.

They provide a standardized way to communicate the outcome of requests, supporting robust error handling and client communication.

The 204 status code indicates the request was successful but no content is returned, so the client should not take further action.

Flask can return a 404 Not Found status code, either by default or using a custom error handler to provide a specific message.