Skip to main content

This project provides collection of utilities for FastAPI framework as: Catcher, Middleware, etc.

Project description

GitHub PyPI - Downloads PyPI

Introduction

This project provides collection of utilities for smooth integration of FastAPI framework with Google Cloud Platform services as logging and tracing.

The key features of this project are:

  • Logging to Cloud Logging
  • Tracing to Cloud Logging
  • Error Reporting via Cloud Logging
  • Custom middleware for configuration of logging
  • Custom exception handlers treating HTTP and validation exceptions
  • Custom routes for documentation and favicon
  • Custom responses with statuses success, warning and error and standardized error messages

Quick Start

This section shows how to use the utilities provided by this project:

"""File main.py with FastAPI app"""
import os
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from fastapi import FastAPI, Request, Query

# import surquest modules and objects
from surquest.fastapi.utils.route import Route  # custom routes for documentation and FavIcon
from surquest.fastapi.utils.GCP.tracer import Tracer
from surquest.fastapi.utils.GCP.logging import Logger
from surquest.fastapi.schemas.responses import Response
from surquest.fastapi.utils.GCP.middleware import LoggingMiddleware
from surquest.fastapi.utils.GCP.catcher import (
    catch_validation_exceptions,
    catch_http_exceptions,
)

PATH_PREFIX = os.getenv('PATH_PREFIX','')

app = FastAPI(
    title="Exchange Rates ETL",
    openapi_url=F"{PATH_PREFIX}/openapi.json"
)

# add middleware
app.add_middleware(LoggingMiddleware)

# exception handlers
app.add_exception_handler(HTTPException, catch_http_exceptions)
app.add_exception_handler(RequestValidationError, catch_validation_exceptions)

# custom routes to documentation and favicon
app.add_api_route(path=F"{PATH_PREFIX}/", endpoint=Route.get_documentation, include_in_schema=False)
app.add_api_route(path=PATH_PREFIX, endpoint=Route.get_favicon, include_in_schema=False)

# custom route to illustrate logging and tracing
@app.get(F"{PATH_PREFIX}/users")
async def get_users(
    age: int = Query(
        default=18,
        description="Minimal age of the user",
        example=30,

    ),
):

    with Tracer.start_span("Generate users"):

        users = [
            {"name": "John Doe", "age": 30, "email": "john@doe.com"},
            {"name": "Will Smith", "age": 42, "email": "will@smith.com"}
        ]

        Logger.info('Found %s users', len(users), extra={"users": users})

    with Tracer.start_span("Filtering users"):

        output = []
        excluded = []
        Logger.debug(F"Filtering users by age > {age}")

        for user in users:

            if user["age"] > age:
                output.append(user)
            else:
                excluded.append(user)

        Logger.debug(
            'Number of excluded users: %s', len(excluded),
            extra={"excluded": excluded}
        )

    return Response.set(data=output)

The endpoint /users will return the following standard response:

{
  "info": {
    "status": "success"
  },
  "data": [
    {
      "name": "John Doe",
      "age": 30,
      "email": "john@doe.com"
    },
    {
      "name": "Will Smith",
      "age": 42,
      "email": "will@smith.com"
    }
  ]
}

and the logs will are available in Google Cloud Platform console within Stackdriver Logging:

Log Entries

as well as the traces are available in Google Cloud Platform console within Stackdriver Trace:

Trace

Local development

You are more than welcome to contribute to this project. To make your start easier we have prepared a docker image with all the necessary tools to run it as interpreter for Pycharm or to run tests.

Build docker image

docker build `
     --tag surquest/fastapi/utils `
     --file package.base.dockerfile `
     --target test .

Run tests

docker run --rm -it `
 -v "${pwd}:/opt/project" `
 -e "GOOGLE_APPLICATION_CREDENTIALS=/opt/project/credentials/keyfile.json" `
 -w "/opt/project/test" `
 surquest/fastapi/utils pytest

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

surquest_fastapi_utils-0.2.6.tar.gz (111.4 kB view details)

Uploaded Source

Built Distribution

surquest_fastapi_utils-0.2.6-py2.py3-none-any.whl (16.1 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file surquest_fastapi_utils-0.2.6.tar.gz.

File metadata

File hashes

Hashes for surquest_fastapi_utils-0.2.6.tar.gz
Algorithm Hash digest
SHA256 cc203ba305fd521172719c06d46022a06ba1eb6565e5e6dbd9cb2a6f691f97be
MD5 dcc2ee640013cce3f7289ef73287061f
BLAKE2b-256 6b4d4125d9256a731fe6d22e643561de7297395182e5d954d2d5aa6fbdf5edcb

See more details on using hashes here.

File details

Details for the file surquest_fastapi_utils-0.2.6-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for surquest_fastapi_utils-0.2.6-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 771936e3fa53b8f2b1ccb0f1efdcb8994857bf53eb705df6308139f6b52376ef
MD5 21db0a6483eec98944079b6f27c1c46f
BLAKE2b-256 1b2e6be98894e2b90caa8e04974e192441366cef7332002df73164db26f903e3

See more details on using hashes here.

Supported by

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