### Install Local Package
Source: https://github.com/moesif/moesifasgi/blob/master/BUILDING.md
Install the moesifasgi package from a local tar.gz file using pip. Ensure your virtual environment is activated.
```bash
pip install --user path/to/moesifasgi.tar.gz
```
--------------------------------
### Set Up Virtual Environment
Source: https://github.com/moesif/moesifasgi/blob/master/BUILDING.md
Before installing locally, it is recommended to set up a virtual environment. Activate it using 'source bin/activate'.
```bash
virtual ENV
```
```bash
source bin/activate
```
--------------------------------
### Complete Production Configuration Example
Source: https://context7.com/moesif/moesifasgi/llms.txt
A comprehensive example demonstrating various Moesif ASGI settings for production, including hook functions for user/company identification, metadata, skipping requests, and masking sensitive data.
```python
import os
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
# ---- Hook functions ----
def identify_user(request, response):
return request.headers.get("X-User-Id")
def identify_company(request, response):
return request.headers.get("X-Org-Id")
def get_metadata(request, response):
return {
'region': os.getenv('AWS_REGION', 'us-east-1'),
'version': os.getenv('APP_VERSION', '1.0.0'),
}
def should_skip(request, response):
return str(request.url).endswith("/health") or str(request.url).endswith("/metrics")
def mask_event(event_model):
sensitive = ['password', 'credit_card', 'cvv', 'ssn']
for body in [event_model.request.body, event_model.response.body]:
if isinstance(body, dict):
for key in sensitive:
if key in body:
body[key] = '[REDACTED]'
return event_model
# ---- Settings ----
moesif_settings = {
'APPLICATION_ID': os.environ['MOESIF_APPLICATION_ID'],
'LOG_BODY': True,
'DEBUG': os.getenv('ENV') == 'development',
'IDENTIFY_USER': identify_user,
'IDENTIFY_COMPANY': identify_company,
'GET_METADATA': get_metadata,
'SKIP': should_skip,
'MASK_EVENT_MODEL': mask_event,
'BATCH_SIZE': 200,
'EVENT_QUEUE_SIZE': 500000,
'EVENT_BATCH_TIMEOUT': 2,
'CAPTURE_OUTGOING_REQUESTS': True,
'AUTHORIZATION_HEADER_NAME': 'Authorization,X-Api-Key',
'AUTHORIZATION_USER_ID_FIELD': 'sub',
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
@app.get("/api/v1/items")
async def list_items():
return [{"id": 1, "name": "Widget"}, {"id": 2, "name": "Gadget"}]
@app.get("/health")
async def health():
return {"status": "ok"} # Not logged to Moesif
```
--------------------------------
### Install Moesif ASGI Middleware
Source: https://github.com/moesif/moesifasgi/blob/master/README.md
Install the moesifasgi package using pip. This is the first step to integrating Moesif with your ASGI application.
```shell
pip install moesifasgi
```
--------------------------------
### Configure Moesif Middleware Settings
Source: https://github.com/moesif/moesifasgi/blob/master/README.md
Configure Moesif middleware settings, including application ID, logging preferences, and custom identification/masking functions. This setup is for non-async modes.
```python
# identify user not using async mode
def identify_user(request, response):
return "12345"
# identify company not using async mode
def identify_company(request, response):
return "67890"
# get metadata not using async mode
def get_metadata(request, response):
return {
'datacenter': 'westus',
'deployment_version': 'v1.2.3',
}
# should skip check not using async mode
def should_skip(request, response):
return "health/probe" in request.url._url
# mask event not using async mode
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
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'LOG_BODY': True,
'DEBUG': False,
'IDENTIFY_USER': identify_user,
'IDENTIFY_COMPANY': identify_company,
'GET_METADATA': get_metadata,
'SKIP': should_skip,
'MASK_EVENT_MODEL': mask_event,
'CAPTURE_OUTGOING_REQUESTS': False,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```
--------------------------------
### Configure Moesif Middleware with Outgoing Request Capture
Source: https://github.com/moesif/moesifasgi/blob/master/README.md
Enable capturing outgoing API calls to third-party services by setting CAPTURE_OUTGOING_REQUESTS to True. This example also includes basic settings like APPLICATION_ID and LOG_BODY.
```python
from moesifasgi import MoesifMiddleware
moesif_settings = {
'APPLICATION_ID': 'YOUR_APPLICATION_ID',
'LOG_BODY': True,
'CAPTURE_OUTGOING_REQUESTS': False,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```
--------------------------------
### Get Session Token with GET_SESSION_TOKEN Hook
Source: https://context7.com/moesif/moesifasgi/llms.txt
Configure the GET_SESSION_TOKEN hook to return a session token string for associating related API calls within a session. If not provided, Moesif attempts to auto-detect tokens from standard headers.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
def get_session_token(request, response):
# Extract session from a cookie or custom header
return request.cookies.get("session_id") or request.headers.get("X-Session-Token")
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'GET_SESSION_TOKEN': get_session_token,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```
--------------------------------
### Build Distributable Package
Source: https://github.com/moesif/moesifasgi/blob/master/BUILDING.md
Run this command from the root folder to create a 'dist' directory containing your new package.
```bash
python setup.py sdist
```
--------------------------------
### Batch Update User Profiles with Moesif ASGI
Source: https://context7.com/moesif/moesifasgi/llms.txt
Use `update_users_batch` for more efficient updates when sending multiple user profiles to Moesif in a single API call. Ideal for migrations or bulk onboarding.
```python
from moesifasgi import MoesifMiddleware
moesif_settings = {'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID'}
middleware = MoesifMiddleware(app=None, settings=moesif_settings)
users = [
{'user_id': 'u001', 'metadata': {'email': 'alice@example.com', 'plan': 'pro'}},
{'user_id': 'u002', 'metadata': {'email': 'bob@example.com', 'plan': 'free'}},
{'user_id': 'u003', 'metadata': {'email': 'carol@example.com', 'plan': 'enterprise'}},
]
middleware.update_users_batch(users)
# All three user profiles are upserted in Moesif in one request.
```
--------------------------------
### Uninstall Package
Source: https://github.com/moesif/moesifasgi/blob/master/BUILDING.md
Use this command to uninstall the moesifasgi package.
```bash
pip uninstall moesifasgi
```
--------------------------------
### Configure Moesif Middleware in FastAPI
Source: https://github.com/moesif/moesifasgi/blob/master/README.md
Add MoesifMiddleware to a FastAPI application using the add_middleware method. Ensure you replace 'YOUR_APPLICATION_ID' with your actual Moesif Application ID. LOG_BODY can be set to True to log request and response bodies.
```python
from moesifasgi import MoesifMiddleware
moesif_settings = {
'APPLICATION_ID': 'YOUR_APPLICATION_ID',
'LOG_BODY': True,
# ... For other options see below.
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```
--------------------------------
### Update User Profile with Moesif ASGI
Source: https://context7.com/moesif/moesifasgi/llms.txt
Use `update_user` to send individual user profile updates to Moesif. This is useful for keeping user attributes like name, email, or plan in sync with your system.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
moesif_settings = {'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID'}
app = FastAPI()
middleware = MoesifMiddleware(app=None, settings=moesif_settings)
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
@app.post("/register")
async def register(user_id: str, email: str, plan: str):
# ... create user in your DB ...
# Sync user profile to Moesif
middleware.update_user({
'user_id': user_id,
'metadata': {
'email': email,
'plan': plan,
'registered_at': '2024-06-01T00:00:00Z',
}
})
return {"status": "created"}
```
--------------------------------
### Capture Outgoing HTTP Requests with Moesif ASGI
Source: https://context7.com/moesif/moesifasgi/llms.txt
Enable `CAPTURE_OUTGOING_REQUESTS` to automatically log outgoing HTTP calls made by your application using the `requests` library. Companion hooks allow customization of what is logged.
```python
from fastapi import FastAPI
import requests
from moesifasgi import MoesifMiddleware
def skip_outgoing(req, res):
# Don't log calls to your own internal services
return "internal.mycompany.com" in req.url
def get_metadata_outgoing(req, res):
return {'upstream_service': req.url.split('/')[2]}
def identify_user_outgoing(req, res):
# Propagate the same user context to outgoing calls
return req.headers.get("X-User-Id")
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'CAPTURE_OUTGOING_REQUESTS': True, # Enable outgoing capture
'LOG_BODY_OUTGOING': True,
'SKIP_OUTGOING': skip_outgoing,
'GET_METADATA_OUTGOING': get_metadata_outgoing,
'IDENTIFY_USER_OUTGOING': identify_user_outgoing,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
@app.get("/weather")
async def get_weather(city: str):
# This outgoing call to a third-party API is automatically captured
resp = requests.get(f"https://api.weather.example.com/forecast?city={city}")
return resp.json()
```
--------------------------------
### Batch Update Company Profiles with Moesif ASGI
Source: https://context7.com/moesif/moesifasgi/llms.txt
Use `update_companies_batch` to send multiple company profile updates to Moesif in a single API call. This is more efficient than individual updates for bulk operations.
```python
from moesifasgi import MoesifMiddleware
moesif_settings = {'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID'}
middleware = MoesifMiddleware(app=None, settings=moesif_settings)
companies = [
{'company_id': 'c001', 'metadata': {'name': 'Acme Corp', 'plan': 'enterprise', 'seats': 120}},
{'company_id': 'c002', 'metadata': {'name': 'Globex Inc', 'plan': 'pro', 'seats': 10}},
]
middleware.update_companies_batch(companies)
```
--------------------------------
### update_users_batch
Source: https://context7.com/moesif/moesifasgi/llms.txt
Sends multiple user profile updates to Moesif in a single API call. This is more efficient than calling `update_user` in a loop, especially during migrations or bulk onboarding.
```APIDOC
## update_users_batch — Batch Update User Profiles
`update_users_batch(user_profiles: list)` sends multiple user profile updates to Moesif in a single API call. More efficient than calling `update_user` in a loop during migrations or bulk onboarding.
```python
from moesifasgi import MoesifMiddleware
moesif_settings = {'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID'}
middleware = MoesifMiddleware(app=None, settings=moesif_settings)
users = [
{'user_id': 'u001', 'metadata': {'email': 'alice@example.com', 'plan': 'pro'}},
{'user_id': 'u002', 'metadata': {'email': 'bob@example.com', 'plan': 'free'}},
{'user_id': 'u003', 'metadata': {'email': 'carol@example.com', 'plan': 'enterprise'}},
]
middleware.update_users_batch(users)
# All three user profiles are upserted in Moesif in one request.
```
```
--------------------------------
### Update Company Profile with Moesif ASGI
Source: https://context7.com/moesif/moesifasgi/llms.txt
Use `update_company` to send individual company or organization profile updates to Moesif. This is useful for syncing subscription tiers, plan changes, or custom B2B attributes.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
moesif_settings = {'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID'}
app = FastAPI()
middleware = MoesifMiddleware(app=None, settings=moesif_settings)
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
@app.post("/billing/upgrade")
async def upgrade(company_id: str, new_plan: str):
# ... handle billing ...
middleware.update_company({
'company_id': company_id,
'metadata': {
'plan': new_plan,
'upgraded_at': '2024-06-15T12:00:00Z',
'mrr': 299.00,
}
})
return {"status": "upgraded"}
```
--------------------------------
### Secure Proxy Configuration with BASE_URI
Source: https://context7.com/moesif/moesifasgi/llms.txt
Override the default Moesif collector endpoint using `BASE_URI`. This is necessary when routing traffic through a Moesif Secure Proxy.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'BASE_URI': 'https://moesif-proxy.mycompany.internal', # Your secure proxy URL
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```
--------------------------------
### Add Custom Metadata with GET_METADATA Hook
Source: https://context7.com/moesif/moesifasgi/llms.txt
Use the GET_METADATA hook to attach custom, JSON-serializable metadata to every logged event. This is useful for tagging events with deployment information, datacenter regions, or feature flags.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
import os
def get_metadata(request, response):
return {
'environment': os.getenv('ENV', 'production'),
'datacenter': 'us-west-2',
'deployment_version': 'v2.4.1',
'feature_flags': ['new_checkout', 'dark_mode'],
}
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'GET_METADATA': get_metadata,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
# Every event in Moesif will carry the metadata dictionary.
```
--------------------------------
### update_companies_batch
Source: https://context7.com/moesif/moesifasgi/llms.txt
Sends multiple company profile updates in a single Moesif API call. This is efficient for bulk updates.
```APIDOC
## update_companies_batch — Batch Update Company Profiles
`update_companies_batch(companies_profiles: list)` sends multiple company profile updates in a single Moesif API call.
```python
from moesifasgi import MoesifMiddleware
moesif_settings = {'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID'}
middleware = MoesifMiddleware(app=None, settings=moesif_settings)
companies = [
{'company_id': 'c001', 'metadata': {'name': 'Acme Corp', 'plan': 'enterprise', 'seats': 120}},
{'company_id': 'c002', 'metadata': {'name': 'Globex Inc', 'plan': 'pro', 'seats': 10}},
]
middleware.update_companies_batch(companies)
```
```
--------------------------------
### CAPTURE_OUTGOING_REQUESTS
Source: https://context7.com/moesif/moesifasgi/llms.txt
When set to True, the middleware monkey-patches the Python `requests` library to intercept and log all outgoing HTTP calls. Companion hooks allow customization of this behavior.
```APIDOC
## CAPTURE_OUTGOING_REQUESTS — Outgoing HTTP Call Capture
When `CAPTURE_OUTGOING_REQUESTS` is set to `True`, the middleware monkey-patches the Python `requests` library to intercept and log all outgoing HTTP calls your application makes to third-party services. Companion hooks (`SKIP_OUTGOING`, `IDENTIFY_USER_OUTGOING`, `IDENTIFY_COMPANY_OUTGOING`, `GET_METADATA_OUTGOING`, `GET_SESSION_TOKEN_OUTGOING`, `LOG_BODY_OUTGOING`) mirror their incoming counterparts but operate on `requests` library request/response objects.
```python
from fastapi import FastAPI
import requests
from moesifasgi import MoesifMiddleware
def skip_outgoing(req, res):
# Don't log calls to your own internal services
return "internal.mycompany.com" in req.url
def get_metadata_outgoing(req, res):
return {'upstream_service': req.url.split('/')[2]}
def identify_user_outgoing(req, res):
# Propagate the same user context to outgoing calls
return req.headers.get("X-User-Id")
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'CAPTURE_OUTGOING_REQUESTS': True, # Enable outgoing capture
'LOG_BODY_OUTGOING': True,
'SKIP_OUTGOING': skip_outgoing,
'GET_METADATA_OUTGOING': get_metadata_outgoing,
'IDENTIFY_USER_OUTGOING': identify_user_outgoing,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
@app.get("/weather")
async def get_weather(city: str):
# This outgoing call to a third-party API is automatically captured
resp = requests.get(f"https://api.weather.example.com/forecast?city={city}")
return resp.json()
```
```
--------------------------------
### update_user
Source: https://context7.com/moesif/moesifasgi/llms.txt
Updates a single user profile in Moesif. Use this to keep user attributes like name, email, plan, and custom properties synchronized with your user management system.
```APIDOC
## update_user — Update a User Profile
`update_user(user_profile: dict)` sends a user profile update directly to Moesif outside of the request/response flow. Use this to keep user attributes (name, email, plan, custom properties) in sync with your own user management system.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
moesif_settings = {'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID'}
app = FastAPI()
middleware = MoesifMiddleware(app=None, settings=moesif_settings)
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
@app.post("/register")
async def register(user_id: str, email: str, plan: str):
# ... create user in your DB ...
# Sync user profile to Moesif
middleware.update_user({
'user_id': user_id,
'metadata': {
'email': email,
'plan': plan,
'registered_at': '2024-06-01T00:00:00Z',
}
})
return {"status": "created"}
```
```
--------------------------------
### Auto User ID Extraction with Authorization Header
Source: https://context7.com/moesif/moesifasgi/llms.txt
Configure Moesif to automatically extract user IDs from specified authorization headers and JWT claims. This is useful when `IDENTIFY_USER` is not explicitly provided.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
# Check X-Api-Key first, then fall back to Authorization
'AUTHORIZATION_HEADER_NAME': 'X-Api-Key,Authorization',
# Extract "user_id" claim from JWT payload instead of default "sub"
'AUTHORIZATION_USER_ID_FIELD': 'user_id',
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
# A request with: Authorization: Bearer eyJ...{"user_id":"abc123"}...
# will automatically be tagged with user ID "abc123" in Moesif.
```
--------------------------------
### Custom User Identification with IDENTIFY_USER Hook
Source: https://context7.com/moesif/moesifasgi/llms.txt
Implement a custom user identification strategy by providing a callable to the `IDENTIFY_USER` setting. This function can be sync or async and should return the user ID.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
# Sync version
def identify_user(request, response):
# Extract user_id from a custom header, JWT claim, or request state
return request.headers.get("X-User-Id", "anonymous")
# Async version (also supported)
async def identify_user_async(request, response):
# Could perform an async DB lookup here
token = request.headers.get("Authorization", "")
return token.split("user:")[-1] if "user:" in token else None
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'IDENTIFY_USER': identify_user, # or identify_user_async
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
# All events will now carry the resolved user ID in Moesif.
```
--------------------------------
### Filter Events with SKIP Hook
Source: https://context7.com/moesif/moesifasgi/llms.txt
Implement the SKIP hook to conditionally suppress logging for specific request/response pairs. This is ideal for excluding health checks, internal probes, static assets, or other non-essential routes from Moesif logs.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
def should_skip(request, response):
url = str(request.url)
# Skip health probes, metrics endpoints, and static files
skip_paths = ["/health", "/metrics", "/readyz", "/livez", "/static"]
return any(url.endswith(p) or p in url for p in skip_paths)
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'SKIP': should_skip,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
@app.get("/health")
async def health():
return {"status": "ok"} # This route will NOT be logged to Moesif.
@app.get("/api/users")
async def list_users():
return [] # This route WILL be logged.
```
--------------------------------
### LOG_BODY_OUTGOING
Source: https://github.com/moesif/moesifasgi/blob/master/README.md
A boolean setting to control whether request and response bodies are logged. Defaults to True.
```APIDOC
## LOG_BODY_OUTGOING
### Description
Set to `False` to remove logging request and response body.
### Data Type
Boolean
### Default
True
### Optional
Optional.
```
--------------------------------
### GET_SESSION_TOKEN_OUTGOING
Source: https://github.com/moesif/moesifasgi/blob/master/README.md
A function that takes Requests request and response objects, and returns a string that corresponds to the session token for this event. This is an optional function.
```APIDOC
## GET_SESSION_TOKEN_OUTGOING
### Description
A function that takes Requests request and response objects, and returns a string that corresponds to the session token for this event. Similar to user IDs, Moesif tries to get the session token automatically. However, if your setup differs from the standard, this function can help tying up events together and help you replay the events.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Function Signature
(req, res)
### Return Type
String
### Optional
Optional.
```
--------------------------------
### Mask Sensitive Data with MASK_EVENT_MODEL Hook
Source: https://context7.com/moesif/moesifasgi/llms.txt
Use the MASK_EVENT_MODEL hook to modify or nullify sensitive fields within the event object before it's uploaded to Moesif. This ensures that PII, passwords, credit card numbers, and other sensitive data are not logged.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
def mask_event(event_model):
# Mask sensitive fields in request body
if event_model.request.body and isinstance(event_model.request.body, dict):
for field in ['password', 'credit_card', 'ssn', 'token']:
if field in event_model.request.body:
event_model.request.body[field] = '***MASKED***'
# Mask sensitive fields in response body
if event_model.response.body and isinstance(event_model.response.body, dict):
for field in ['secret_key', 'api_token']:
if field in event_model.response.body:
event_model.response.body[field] = None
# Remove a sensitive request header entirely
if event_model.request.headers:
event_model.request.headers.pop('X-Internal-Secret', None)
return event_model
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'LOG_BODY': True,
'MASK_EVENT_MODEL': mask_event,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```
--------------------------------
### update_company
Source: https://context7.com/moesif/moesifasgi/llms.txt
Updates a company or organization profile in Moesif. Useful for synchronizing subscription tier, plan changes, or custom B2B attributes after billing events.
```APIDOC
## update_company — Update a Company Profile
`update_company(company_profile: dict)` sends a company/organization profile update to Moesif. Useful for syncing subscription tier, plan changes, or custom B2B attributes after billing events.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
moesif_settings = {'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID'}
app = FastAPI()
middleware = MoesifMiddleware(app=None, settings=moesif_settings)
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
@app.post("/billing/upgrade")
async def upgrade(company_id: str, new_plan: str):
# ... handle billing ...
middleware.update_company({
'company_id': company_id,
'metadata': {
'plan': new_plan,
'upgraded_at': '2024-06-15T12:00:00Z',
'mrr': 299.00,
}
})
return {"status": "upgraded"}
```
```
--------------------------------
### Custom Company Identification with IDENTIFY_COMPANY Hook
Source: https://context7.com/moesif/moesifasgi/llms.txt
Link API calls to specific organizations using the `IDENTIFY_COMPANY` hook. Provide a callable that returns the company ID, typically extracted from headers or JWT claims.
```python
from fastapi import FastAPI
from moesifasgi import MoesifMiddleware
def identify_company(request, response):
# Read tenant/org ID from a custom header or JWT claim
return request.headers.get("X-Org-Id", "unknown-company")
moesif_settings = {
'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
'IDENTIFY_USER': lambda req, res: req.headers.get("X-User-Id"),
'IDENTIFY_COMPANY': identify_company,
}
app = FastAPI()
app.add_middleware(MoesifMiddleware, settings=moesif_settings)
# Events in Moesif will be linked to both user and company.
```
--------------------------------
### IDENTIFY_COMPANY_OUTGOING
Source: https://github.com/moesif/moesifasgi/blob/master/README.md
A function that takes Requests request and response objects, and returns a string that represents the company ID for this event. This is an optional function.
```APIDOC
## IDENTIFY_COMPANY_OUTGOING
### Description
A function that takes Requests request and response objects, and returns a string that represents the company ID for this event.
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Function Signature
(req, res)
### Return Type
String
### Optional
Optional.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.