Skip to main content

Moesif Middleware for Python ASGI based platforms (FastAPI & Others)

Project description

Moesif Middleware for Python ASGI based Frameworks

Built For Latest Version Language Versions Software License Source Code

ASGI middleware that automatically logs incoming or outgoing API calls and sends to Moesif for API analytics and monitoring. Supports Python Frameworks built on ASGI such as FastAPI and more.

Source Code on GitHub

ASGI (Asynchronous Server Gateway Interface) is a spiritual successor to WSGI, intended to provide a standard interface between async-capable Python web servers, frameworks, and applications. Many Python Frameworks are build on top of ASGI, such as FastAPI, etc. Moesif ASGI Middleware help APIs that are build on top of these Frameworks to easily integrate with Moesif.

How to install

pip install moesifasgi

How to use

FastAPI

Add Moesif middleware to fastAPI app.

from moesifasgi import MoesifMiddleware

moesif_settings = {
    'APPLICATION_ID': 'Your Moesif Application id',
    'LOG_BODY': True,
    # ... For other options see below.
}

app = FastAPI()

app.add_middleware(MoesifMiddleware, settings=moesif_settings)

Your Moesif Application Id can be found in the Moesif Portal. After signing up for a Moesif account, your Moesif Application Id will be displayed during the onboarding steps.

You can always find your Moesif Application Id at any time by logging into the Moesif Portal, click on the top right menu, and then clicking API Keys.

For an example with Flask, see example in the /examples/flask folder of this repo.

Other ASGI frameworks

If you are using a framework that is built on top of ASGI, it should work just by adding the Moesif middleware. Please read the documentation for your specific framework on how to add middleware.

Configuration options

APPLICATION_ID

(required), string, is obtained via your Moesif Account, this is required.

For options that use the request and response as input arguments, these use the Requests and Responses objects respectively.

SKIP

(optional) (request, response) => boolean, a function that takes a request and a response, and returns true if you want to skip this particular event.

IDENTIFY_USER

(optional, but highly recommended) (request, response) => string, a function that takes a request and a response, and returns a string that is the user id used by your system. While Moesif tries to identify users automatically, but different frameworks and your implementation might be very different, it would be helpful and much more accurate to provide this function.

IDENTIFY_COMPANY

(optional) (request, response) => string, a function that takes a request and a response, and returns a string that is the company id for this event.

GET_METADATA

(optional) (request, response) => dictionary, a function that takes a request and a response, and returns a dictionary (must be able to be encoded into JSON). This allows your to associate this event with custom metadata. For example, you may want to save a VM instance_id, a trace_id, or a tenant_id with the request.

GET_SESSION_TOKEN

(optional) (request, response) => string, a function that takes a request and a response, and returns a string that is the session token for this event. Again, Moesif tries to get the session token automatically, but if you setup is very different from standard, this function will be very help for tying events together, and help you replay the events.

MASK_EVENT_MODEL

(optional) (EventModel) => EventModel, a function that takes an EventModel and returns an EventModel with desired data removed. The return value must be a valid EventModel required by Moesif data ingestion API. For details regarding EventModel please see the Moesif Python API Documentation.

DEBUG

(optional) boolean, a flag to see debugging messages.

LOG_BODY

(optional) boolean, default True, Set to False to remove logging request and response body.

BATCH_SIZE

(optional) int, default 25, Maximum batch size when sending events to Moesif.

AUTHORIZATION_HEADER_NAME

(optional) string, A request header field name used to identify the User in Moesif. Default value is authorization. Also, supports a comma separated string. We will check headers in order like "X-Api-Key,Authorization".

AUTHORIZATION_USER_ID_FIELD

(optional) string, A field name used to parse the User from authorization header in Moesif. Default value is sub.

BASE_URI

(optional) string, A local proxy hostname when sending traffic via secure proxy. Please set this field when using secure proxy. For more details, refer secure proxy documentation.

Options specific to outgoing API calls

The options below are applicable to outgoing API calls (calls you initiate using the Python Requests lib to third parties like Stripe or to your own services).

For options that use the request and response as input arguments, these use the Requests lib's request or response objects.

If you are not using ASGI, you can import the moesifpythonrequest directly.

CAPTURE_OUTGOING_REQUESTS

boolean, Default False. Set to True to capture all outgoing API calls. False will disable this functionality.

GET_METADATA_OUTGOING

(optional) (req, res) => dictionary, a function that enables you to return custom metadata associated with the logged API calls. Takes in the Requests request and response object as arguments. You should implement a function that returns a dictionary containing your custom metadata. (must be able to be encoded into JSON). For example, you may want to save a VM instance_id, a trace_id, or a resource_id with the request.

SKIP_OUTGOING

(optional) (req, res) => boolean, a function that takes a Requests request and response, and returns true if you want to skip this particular event.

IDENTIFY_USER_OUTGOING

(optional, but highly recommended) (req, res) => string, a function that takes Requests request and response, and returns a string that is the user id used by your system. While Moesif tries to identify users automatically, but different frameworks and your implementation might be very different, it would be helpful and much more accurate to provide this function.

IDENTIFY_COMPANY_OUTGOING

(optional) (req, res) => string, a function that takes Requests request and response, and returns a string that is the company id for this event.

GET_SESSION_TOKEN_OUTGOING

(optional) (req, res) => string, a function that takes Requests request and response, and returns a string that is the session token for this event. Again, Moesif tries to get the session token automatically, but if you setup is very different from standard, this function will be very help for tying events together, and help you replay the events.

LOG_BODY_OUTGOING

(optional) boolean, default True, Set to False to remove logging request and response body.

Example:

def identify_user(request, response):
    # Your custom code that returns a user id string
    return "12345"

def identify_company(request, response):
    # Your custom code that returns a company id string
    return "67890"

def should_skip(request, response):
    # Your custom code that returns true to skip logging
    return "health/probe" in request.url._url

def get_token(request, response):
    # If you don't want to use the standard ASGI session token,
    # add your custom code that returns a string for session/API token
    return "XXXXXXXXXXXXXX"

def mask_event(eventmodel):
    # Your custom code to change or remove any sensitive fields
    if 'password' in eventmodel.response.body:
        eventmodel.response.body['password'] = None
    return eventmodel

def get_metadata(request, response):
    return {
        'datacenter': 'westus',
        'deployment_version': 'v1.2.3',
    }

moesif_settings = {
    'APPLICATION_ID': 'Your Moesif Application Id',
    'DEBUG': False,
    'LOG_BODY': True,
    'IDENTIFY_USER': identify_user,
    'IDENTIFY_COMPANY': identify_company,
    'GET_SESSION_TOKEN': get_token,
    'SKIP': should_skip,
    'MASK_EVENT_MODEL': mask_event,
    'GET_METADATA': get_metadata,
    'CAPTURE_OUTGOING_REQUESTS': False
}

app = FastAPI()

app.add_middleware(MoesifMiddleware, settings=moesif_settings)

Other integrations

To view more documentation on integration options, please visit the Integration Options Documentation.

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

moesifasgi-0.0.2.tar.gz (21.5 kB view details)

Uploaded Source

Built Distribution

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

moesifasgi-0.0.2-py2.py3-none-any.whl (21.0 kB view details)

Uploaded Python 2Python 3

File details

Details for the file moesifasgi-0.0.2.tar.gz.

File metadata

  • Download URL: moesifasgi-0.0.2.tar.gz
  • Upload date:
  • Size: 21.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/3.10.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.7.10

File hashes

Hashes for moesifasgi-0.0.2.tar.gz
Algorithm Hash digest
SHA256 7cd85e9395b06cbb913c0c29af984a3fbdda8e902b0f1489060618f5c9bb1c8b
MD5 d77d12fe64007ecbe2a3f67b76a72cf8
BLAKE2b-256 294f935dbb2837a8a07c9749fd664fa84929115c5fa000f0aaab3f04fe98aa93

See more details on using hashes here.

File details

Details for the file moesifasgi-0.0.2-py2.py3-none-any.whl.

File metadata

  • Download URL: moesifasgi-0.0.2-py2.py3-none-any.whl
  • Upload date:
  • Size: 21.0 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/3.10.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.7.10

File hashes

Hashes for moesifasgi-0.0.2-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 5f660a04098463fcb89db47d6626e8971f0d0c22aa3d999c900fcc93bd673b1b
MD5 711df2275a9f3caf55eff026e44d179c
BLAKE2b-256 83a8fb5f6bfdb9708d3431fef2f6409075f7a3c365b65d19e4be78b9b845b14e

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