0
0
Rest APIprogramming~5 mins

Problem Details (RFC 7807) format in Rest API

Choose your learning style9 modes available
Introduction

This format helps APIs explain errors clearly and consistently. It makes it easier for clients to understand what went wrong.

When your API needs to send error information to clients.
When you want to standardize error messages across different parts of your API.
When you want clients to handle errors in a predictable way.
When debugging problems between client and server.
When you want to provide helpful links or details about errors.
Syntax
Rest API
{
  "type": "string (URI)",
  "title": "string",
  "status": "integer (HTTP status code)",
  "detail": "string",
  "instance": "string (URI)",
  "additional_fields": "optional extra info"
}

type is a URI that identifies the error type. It should be a URL but does not have to be reachable.

title is a short, human-readable summary of the problem.

Examples
This example shows a user error about insufficient credit with details and a link to the specific request.
Rest API
{
  "type": "https://example.com/probs/out-of-credit",
  "title": "You do not have enough credit.",
  "status": 403,
  "detail": "Your current balance is 30, but that costs 50.",
  "instance": "/account/12345/transactions/abc"
}
This example explains a validation error for a user input field.
Rest API
{
  "type": "https://example.com/probs/invalid-input",
  "title": "Invalid input.",
  "status": 400,
  "detail": "The 'email' field must be a valid email address.",
  "instance": "/users/5678"
}
Sample Program

This Flask app returns a Problem Details JSON response with HTTP status 403 and the correct content type when you visit /error.

Rest API
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/error')
def error():
    problem = {
        "type": "https://example.com/probs/out-of-credit",
        "title": "You do not have enough credit.",
        "status": 403,
        "detail": "Your current balance is 30, but that costs 50.",
        "instance": "/account/12345/transactions/abc"
    }
    response = jsonify(problem)
    response.status_code = problem["status"]
    response.headers["Content-Type"] = "application/problem+json"
    return response

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

Always set the HTTP status code to match the status field in the problem details.

Use the Content-Type header value application/problem+json to indicate this format.

You can add extra fields if needed, but keep the standard fields for compatibility.

Summary

Problem Details format standardizes error responses in APIs.

It uses a JSON object with fields like type, title, status, detail, and instance.

This helps clients understand and handle errors better.