Skip to main content

Business validation diagnostics (errors) collection library. With FastAPI support.

Project description

GCM Diagnostics

Library for collecting errors from validation logic and presenting them to user.

Mainly intended to be used with FastAPI endpoints for doing business validation which Pydantic is not intended for. Errors generated by this library are compatible with Pydantic validation response, so it appears the same to the consumer of API.

Installation

pip install gcm_diagnostics

# or

poetry add gcm_diagnostics

Usage

from gcm_diagnostics import DiagnosticCollector
from gcm_diagnostics.errors import EntityNotFound, EntityAlreadyExists

with DiagnosticCollector(prefix=["body"]) as diag:
    diag.append(EntityNotFound(loc=[1, "id"], id=1))
    diag.append(EntityAlreadyExists(loc=[2, "name"], entity="Hello"))

# Here, DiagnosticException is raised, containing both errors.

print(diag.errors)
# [
#     {
#         "loc": ["body", 1, "id"],
#         "msg": "Entity with id 1 not found",
#         "type": "entity_not_found",
#         "id": 1
#     },
#     {
#         "loc": ["body", 2, "name"],
#         "msg": "Entity already exists",
#         "type": "entity_already_exists",
#         "entity": "Hello"
#     }
# ]

Usage with FastAPI

from fastapi import FastAPI
from gcm_diagnostics import install_exception_handler, DiagnosticCollector, diagnostic_schema
from gcm_diagnostics.errors import EntityNotFound
from starlette.testclient import TestClient

app = FastAPI()

# Install exception handler for the DiagnosticError exception.  
install_exception_handler(app)

@app.get(
    "/",
    # This builds responses structure containing documentation for the specified
    # error types this endpoint produces instead of generic error description.
    # Usage of diagnostic_schema() is not required, it is just a convenient
    # helper to build better documentation even for error states.
    responses=diagnostic_schema([EntityNotFound])
)
def diagnostics(id: int) -> None:
    # Instantiate DiagnosticCollector(), that will collect all diagnostic data from
    # validation logic.
    # In this case, all errors will be prefixed with "query" prefix.
    with DiagnosticCollector(prefix=["query"]) as diag:
        # Append new error to the collector. This does not raise exception immediately,
        # it allows to collect multiple errors at one shot, and present it all to the user.
        # Resulting loc for this error will be ["query", "id"].
        diag.append(EntityNotFound(loc=["id"], id=id))
        
        # If you want to raise exception in the middle of validation logic, you can
        # use raise_if_errors() as follows:
        #diag.raise_if_errors()


with TestClient(app, raise_server_exceptions=False) as client:
    response = client.get("/", params={"id": 123})
    
    # Error code is gathered from diagnostics. If there are only diagnostics of one
    # type (with one status code), this status code is returned.
    # If there are multiple different status codes, generic 422 is returned.
    assert response.status_code == 404
    
    # Response is generated from collected diagnostics. All errors are present in the detail array.
    assert response.json() == {
        "detail": [
            {
                "loc": ["query", "id"],
                "msg": "Entity does not exists.",
                "type": "entity_not_found",
                "id": 123
            }
        ]
    }

For more usage details, please consult the documentation in the code, mainly the documentation of class DiagnosticCollector.

Maturity

This library is currently used in various production applications and is considered stable.

Contributing

Contributions are always welcome. Just open an issue or a merge request.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gcm_diagnostics-1.4.1.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gcm_diagnostics-1.4.1-py3-none-any.whl (16.9 kB view details)

Uploaded Python 3

File details

Details for the file gcm_diagnostics-1.4.1.tar.gz.

File metadata

  • Download URL: gcm_diagnostics-1.4.1.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.11.9 Linux/5.15.0-134-generic

File hashes

Hashes for gcm_diagnostics-1.4.1.tar.gz
Algorithm Hash digest
SHA256 04a5d83a6c9392aaed7a0c773d728025f32fd0494cbf11c0d4ca05d6fcb58b20
MD5 d8299e2bcd7dc5be190b35cd8d0d9d61
BLAKE2b-256 843472171fed6ec6289312a052c12226e7eb0aba1d756f9bb01b71e95ce3f954

See more details on using hashes here.

File details

Details for the file gcm_diagnostics-1.4.1-py3-none-any.whl.

File metadata

  • Download URL: gcm_diagnostics-1.4.1-py3-none-any.whl
  • Upload date:
  • Size: 16.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.11.9 Linux/5.15.0-134-generic

File hashes

Hashes for gcm_diagnostics-1.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9735af1c58ada9a20ed70d94aa37b679bcc1d3bb7d140b43d484cb25e527b238
MD5 cda4922d678f76bd27a8567850161223
BLAKE2b-256 1c37444a4fb9c581f8d25bccb1264adb04af5dad00e3210c39478943b6b2ed1b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page