Skip to main content

python-httpproblem

Utility library to work with RFC7807 Problem Details for HTTP APIs.

Build Status sonar-quality-gate sonar-coverage sonar-bugs sonar-vulnerabilities

This library is very light-weight, with no external dependencies, fully-tested and works with both Python 2 and Python 3. It has special support for AWS lambda proxy integration output format but it should be easy to map to any other format or framework. Currently only JSON serialization is supported.

Installation

pip install httpproblem

Usage

Build a Problem dict

The problem() function that can be used to build a dict with the problem fields.

>>> pprint(problem(httplib.BAD_REQUEST, 'You do not have enough credit.', 'Your current balance is 30, but that costs 50.', '/account/12345/msgs/abc'))
{'detail': 'Your current balance is 30, but that costs 50.',
 'status': 400,
 'title': 'You do not have enough credit.',
 'type': '/account/12345/msgs/abc'}

You can also use problem extensions

>>> pprint(problem(httplib.BAD_REQUEST, 'You do not have enough credit.', 'Your current balance is 30, but that costs 50.', '/account/12345/msgs/abc', balance=30, accounts=['/account/12345','/account/67890']))
{'accounts': ['/account/12345', '/account/67890'],
 'balance': 30,
 'detail': 'Your current balance is 30, but that costs 50.',
 'status': 400,
 'title': 'You do not have enough credit.',
 'type': '/account/12345/msgs/abc'}

As specified by Predefined Problem Types:

The “about:blank” URI, when used as a problem type, indicates that the problem has no additional semantics beyond that of the HTTP status code.

When “about:blank” is used, the title SHOULD be the same as the recommended HTTP status phrase for that code (e.g., “Not Found” for 404, and so on), although it MAY be localized to suit client preferences (expressed with the Accept-Language request header).

So if this library will automatically fill the title field if the type is not present or about:blank.

>>> problem(404)
{'status': 404, 'title': 'Not Found'}
>>> problem(httplib.BAD_REQUEST, type='about:blank')
{'status': 400, 'type': 'about:blank', 'title': 'Bad Request'}

Build a Problem HTTP response

The problem_http_response() function helps to build HTTP responses using the format used by the AWS lambda proxy integration. The method will automatically fill the Content-Type header with application/problem+json and the HTTP response code with the status.

>>> pprint(problem_http_response(httplib.BAD_REQUEST))
{'body': '{"status": 400, "type": "about:blank", "title": "Bad Request"}',
 'headers': {'Content-Type': 'application/problem+json'},
 'statusCode': 400}

You can map this to other frameworks. For instance for Flask (or Werkzeug):

>>> problem = problem_http_response(400)
>>> print(flask.Response(problem['body'], status=problem['statusCode'], headers=problem['headers']))
<Response 39 bytes [400 BAD REQUEST]>

By default, json.dumps is used to serialize into JSON. This can be changed by using the set_serialize_function

>>> httpproblem.set_serialize_method(lambda data: json.dumps(data, indent=4))
>>> print(problem_http_response(400)['body'])
{
    "status": 400,
    "title": "Bad Request"
}

Raise a Problem exception

The Problem exception class can be used to simplify the error management with try/except. The class has methods to convert it to a Problem dict or HTTP response.

>>> try:
...     raise Problem(httplib.BAD_REQUEST)
... except Problem as e:
...     print(e.to_dict())
...
{'status': 400, 'title': 'Bad Request'}

The to_dict and to_http_response take a with_traceback argument that can be used to include the traceback. You can also set it globally with the activate_traceback() function. For security reasons, the default is to not include the traceback and it is recommended to not activate it in production.

>>> # Add traceback by call argument
>>> try:
...     raise Problem(httplib.BAD_REQUEST)
... except Problem as e:
...     pprint(e.to_dict(with_traceback=True))
...
{'status': 400,
 'title': 'Bad Request',
 'traceback': 'Traceback (most recent call last):\n  File "<stdin>", line 2, in <module>\nProblem: {\'status\': 400, \'title\': \'Bad Request\'}\n'}
>>>
>>> # Add traceback globally
>>> httpproblem.activate_traceback()
>>> try:
...     raise Problem(httplib.BAD_REQUEST)
... except Problem as e:
...     pprint(e.to_dict())
...
{'status': 400,
 'title': 'Bad Request',
 'traceback': 'Traceback (most recent call last):\n  File "<stdin>", line 2, in <module>\nProblem: {\'status\': 400, \'title\': \'Bad Request\'}\n'}

Metadata

Release files for httpproblem 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for httpproblem 0.2.0
File Size Uploaded
httpproblem-0.2.0.tar.gz 5.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for httpproblem 0.2.0
File Interpreter ABI Platform
httpproblem-0.2.0-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 13.2 kB

Release files / httpproblem-0.2.0.tar.gz

Download URL httpproblem-0.2.0.tar.gz
Size 5.2 kB
Tags Source
SHA-256 checksum
How to use checksums
8434f3e8e61bd57d087e3c2d6f34f85ad18fd0f214b339c15c3239a8aa7b42cf
BLAKE2b-256 checksum
How to use checksums
efdaae53747744535f8d2dce222257bd885ec765d00a7b5a53dcb4d7d9b67a03
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / httpproblem-0.2.0-py2.py3-none-any.whl

Download URL httpproblem-0.2.0-py2.py3-none-any.whl
Size 7.9 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
15a357dc5a613f8fa1a7185c90638ca5408d94b54852f92765cf00440464e084
BLAKE2b-256 checksum
How to use checksums
71f9fefe5e9f97ea6c23e6060a7b62f3f82f1a155fef1a02f6ba5019e9248774
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files

0.1.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page