Example FastAPI application with Moesif middleware for API analytics, configured to identify users and companies from request headers.
-
Create a virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
-
Configure environment variables:
- Copy
.env.exampleto.env - Update the values in
.env:
cp .env.example .env # Edit .env and set: # - MOESIF_APPLICATION_ID (required) # - TEST_USER_ID (optional, for test script) # - TEST_COMPANY_ID (optional, for test script)
- Copy
Start the development server:
uvicorn main:app --reloadThe API will be available at http://localhost:8000
Interactive API documentation: http://localhost:8000/docs
Health check endpoint (not logged by Moesif)
List test products with optional category filter
Query Parameters:
category(optional): Filter by category (e.g., "electronics", "books")
Headers:
X-User-Id: ID of the user making the requestX-Company-Id: ID of the company the user belongs to
Create a test order (requires X-User-Id header)
Headers:
X-User-Id: ID of the user making the request (required)X-Company-Id: ID of the company the user belongs toX-User-Email: Email of the user (captured in metadata)
The application is configured to:
- Identify User: Extract user ID from
X-User-Idheader - Identify Company: Extract company ID from
X-Company-Idheader - Capture Metadata: Extract
X-User-EmailandX-Company-Nameheaders, plus a "source" tag - Skip Logging: Health check endpoint is excluded from logging
Run the included test script to send example API calls:
python test_moesif_tracking.pyThis will:
- Send 2 test API calls (products and orders)
- Show request/response details
- Provide a summary of results
The test script uses TEST_USER_ID and TEST_COMPANY_ID from your .env file.
# Example: Get products with filter
curl -X GET "http://localhost:8000/test/api/products?category=electronics" \
-H "X-User-Id: user_abc" \
-H "X-Company-Id: company_xyz" \
-H "X-User-Email: user@example.com"
# Example: Create order
curl -X POST "http://localhost:8000/test/api/orders" \
-H "Content-Type: application/json" \
-H "X-User-Id: user_abc" \
-H "X-Company-Id: company_xyz" \
-H "X-User-Email: user@example.com" \
-d '{"product_id": "1", "quantity": 2, "total_amount": 599.98}'test-moesifasgi/
├── main.py # FastAPI application with Moesif middleware
├── test_moesif_tracking.py # Test script to send example API calls
├── requirements.txt # Python dependencies
├── .env.example # Example environment variables
├── .env # Your environment variables (create this)
├── .gitignore # Git ignore file
└── README.md # This file
After making API calls, visit your Moesif Dashboard to see:
- API calls grouped by user (X-User-Id)
- API calls grouped by company (X-Company-Id)
- Request/response details
- Additional metadata from headers (email, company_name, source)