- Notifications
You must be signed in to change notification settings - Fork3
Moesif AWS Lambda middleware for Python, for API Monitoring, Analytics, and Monetization.
License
Moesif/moesif-aws-lambda-python
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
byMoesif, theAPI analytics andAPI monetization platform.
With Moesif Python middleware for AWS Lambda, you can automatically log API callsand send them toMoesif for API analytics and monitoring.This middleware allows you to integrate Moesif's API analytics andAPI monetization features into your Python applications with minimal configuration.
If you're new to Moesif, seeour Getting Started resources to quickly get up and running.
We've designed Moesif Python middleware for AWS Lambda for APIs that you hoston AWS Lambda using Amazon API Gateway or Application Load Balanceras a trigger. This middleware expects theLambda proxy integration type. If you're using AWS Lambda with API Gateway,you are most likely using the proxy integration type.
Before using this middleware, make sure you have the following:
After you log intoMoesif Portal, you can get your Moesif Application ID during the onboarding steps. You can always access the Application ID any time by following these steps from Moesif Portal after logging in:
- Select the account icon to bring up the settings menu.
- SelectInstallation orAPI Keys.
- Copy your Moesif Application ID from theCollector Application ID field.
Install withpip
using the following command:
pip install moesif_aws_lambda
See the availableconfiguration options to learn how to configure the middleware for your use case.
frommoesif_aws_lambda.middlewareimportMoesifLoggerimportjsonmoesif_options= {'LOG_BODY':True}@MoesifLogger(moesif_options)deflambda_handler(event,context):return {'statusCode':200,'isBase64Encoded':False,'body':json.dumps({'msg':'Hello from Lambda!' }),'headers': {'Content-Type':'application/json' } }
Important: Make sure you set the
body
field to a JSON-formatted string usingjson.dumps()
. Otherwise, API Gateway returns a502 Bad Gateway
error response.
The middleware expects theMOESIF_APPLICATION_ID
environment variable to be able to connect with your Moesif account and send analytics. This variable holds the value ofyour Moesif Application ID. For instructions on how to set environment variables in Lambda, seeUse Lambda environment variables to configure values in code.
To deploy your Lambda function code with Moesif AWS Lambda middleware, you must archive them in a zip file. For archiving instructions, see ourexample Lambda function repository. Then follow the instructions inAWS Lambda docs to upload and deploy your Lambda function code as a zip file archive.
Finally, grab the URL to your API Gateway or Application Load Balancer and make some HTTP requests using a tool like Postman or cURL.
In order for your events to log to Moesif, you must test using the Amazon API Gateway trigger. Do not invoke your Lambda directly using AWS Console as the payload won't contain a valid HTTP payload.
For a general troubleshooting guide that can help you solve common problems, seeServer Troubleshooting Guide.
Other troubleshooting supports:
.├── eventV1.json├── eventV2.json├── images/├── lambda_function.py├── LICENSE├── moesif_aws_lambda/├── package.sh├── README.md├── requirements.txt├── setup.cfg└── setup.py
These are the most important files:
moesif_aws_lambda/middleware.py
: the middleware librarylambda_function.py
: sample AWS Lambda function using the middleware
The following sections describe the available configuration options for this middleware. You can set these options in a Python object and then pass that object as argument to theMoesifLogger
decorator. Seethe sample AWS Lambda middleware function code for an example.
Data type | Parameters | Return type |
---|---|---|
Function | (event, context) | String |
A function that takes AWS Lambdaevent
andcontext
objects as argumentsand returns a user ID. This allows Moesif to attribute API requests to individual unique usersso you can understand who is calling your API. You can use this simultaneously withidentify_company
to track both individual customers and the companies they are a part of.
defidentify_user(event,context):# your code here, must return a stringreturnevent["requestContext"]["identity"]["cognitoIdentityId"]
Data type | Parameters | Return type |
---|---|---|
Function | (event, context) | String |
A function that takes AWS Lambdaevent
andcontext
objects as argumentsand returns a company ID. If you have a B2B business, this allows Moesif to attributeAPI requests to specific companies or organizations so you can understand which accounts arecalling your API. You can use this simultaneously withidentify_user
to track bothindividual customers and the companies they are a part of.
defidentify_company(event,context):# your code here, must return a stringreturn'7890'}
Data type | Parameters | Return type |
---|---|---|
Function | (event, context) | String |
A function that takes AWS lambdaevent
andcontext
objects as arguments and returns asession token such as an API key.
defget_session_token(event,context):# your code here, must return a string.return'XXXXXXXXX'
Data type | Parameters | Return type |
---|---|---|
Function | (event, context) | String |
A function that takes AWS lambdaevent
andcontext
objects as arguments andreturns a string to tag requests with a specific version of your API.
defget_api_version(event,context):# your code here. must return a string.return'1.0.0'
Data type | Parameters | Return type |
---|---|---|
Function | (event, context) | Object |
A function that takes AWS lambdaevent
andcontext
objects as arguments and returns an object.
This function allows youto add custom metadata that Moesif can associate with the request. The metadata must be a simple Python object that can be converted to JSON.
For example, you may want to save a virtual machine instance ID, a trace ID, or a tenant ID with the request.
defget_metadata(event,context):# your code here:return {'trace_id':context.aws_request_id,'function_name':context.function_name,'request_context':event['requestContext'] }
Data type | Parameters | Return type |
---|---|---|
Function | (event, context) | Boolean |
A function that takes AWS lambdaevent
andcontext
objects as arguments and returnsTrue
if you want to skip the event. Skipping an event means Moesif doesn't log the event.
The following example skips requests to the root path/
:
defshould_skip(event,context):# your code here. must return a boolean.return"/"inevent['path']
Data type | Parameters | Return type |
---|---|---|
Function | (MASK_EVENT_MODEL) | MASK_EVENT_MODEL |
A function that takes the final Moesif event model, rather than the AWS lambda event or context objects, as anargument before the middleware sends the event model object to Moesif.
WithMASK_EVENT_MODEL
, you can make modifications to headers or body such asremoving certain header or body fields.
defmask_event(eventmodel):# remove any field that you don't want to be sent to Moesif.returneventmodel
For an example of how Moesif event model looks like, see theeventV1.json
andeventV2.json
files.
For more information about the different fields of Moesif's event model,seeMoesif Python API documentation.
Data type | Default |
---|---|
Boolean | undefined |
Set toTrue
to print debug logs if you're having integration issues.
Data type | Default |
---|---|
Boolean | True |
Whether to log request and response body to Moesif.
If you want to capture all outgoing API calls from your Python app to third parties likeStripe or to your own dependencies, callstart_capture_outgoing()
to start capturing. This mechanism works bypatchingRequests.
frommoesif_aws_lambda.middlewareimport*start_capture_outgoing(moesif_options)# moesif_options are the configuration options.
The following options are available for capturing and logging outgoing calls. The request and response objects passed in correspond to theRequest
andResponse
objects respectively of the Python Requests library.
Data type | Parameters | Return type |
---|---|---|
Function | (request, response) | Boolean |
This function takes RequestsRequest
andResponse
objects and returnsTrue
if you want to skip this particular event.
Data type | Parameters | Return type |
---|---|---|
Function | (request, response) | String |
Optional, but highly recommended.
This function takes RequestsRequest
andResponse
objects and returns a string that representsthe user ID used by your system. While Moesif tries to identify users automatically, different frameworks and your implementation might be very different. So we highly recommend that you accurately provide auser ID using this function.
Data type | Parameters | Return type |
---|---|---|
Function | (request, response) | String |
Optional.
This function takes RequestsRequest
andResponse
objects and returns a string that representsthe company ID for this event.
Data type | Parameters | Return type |
---|---|---|
Function | (request, response) | Dictionary |
Optional.
This function takes RequestsRequest
andResponse
objects andreturns a Python dictionary. The dictionary must be such that it can be converted intovalid JSON. This allows you to associate this event with custom metadata.
For example, you may want to save a virtual machine instance ID, a trace ID, or a tenant ID with the request.
Data type | Parameters | Return type |
---|---|---|
Function | (request, response) | String |
Optional.
This function takes RequestsRequest
andResponse
objects and returns a string that represents the session token for this event. Similar touser IDs, Moesif tries to get the session token automatically. However, if you setup differs from the standard, this function can help tying up events together and help you replay the events.
Data type | Default |
---|---|
Boolean | True |
Optional.
Whether to log request and response body to Moesif.
See theexample AWS Lambda function that uses this middleware.
The following examples demonstrate how to add and update customer information.
To create or update auser profile in Moesif, use theupdate_user()
function.
frommoesif_aws_lambda.middlewareimport*moesif_options= {'LOG_BODY':True,'DEBUG':True,}# Only user_id is required.# Campaign object is optional, but useful if you want to track ROI of acquisition channels# See https://www.moesif.com/docs/api#users for campaign schema# metadata can be any custom objectuser= {'user_id':'12345','company_id':'67890',# If set, associate user with a company object'campaign': {'utm_source':'google','utm_medium':'cpc','utm_campaign':'adwords','utm_term':'api+tooling','utm_content':'landing' },'metadata': {'email':'john@acmeinc.com','first_name':'John','last_name':'Doe','title':'Software Engineer','sales_info': {'stage':'Customer','lifetime_value':24000,'account_owner':'mary@contoso.com' }, }}update_user(user,moesif_options)
Themetadata
field can contain any customer demographic or other info you want to store. Moesif only requires theuser_id
field.
For more information, see the function documentation inMoesif Python API Reference.
To update a list ofusers in one batch, use theupdate_users_batch()
function.
frommoesif_aws_lambda.middlewareimport*moesif_options= {'LOG_BODY':True,'DEBUG':True,}userA= {'user_id':'12345','company_id':'67890',# If set, associate user with a company object'metadata': {'email':'john@acmeinc.com','first_name':'John','last_name':'Doe','title':'Software Engineer','sales_info': {'stage':'Customer','lifetime_value':24000,'account_owner':'mary@contoso.com' }, }}userB= {'user_id':'54321','company_id':'67890',# If set, associate user with a company object'metadata': {'email':'mary@acmeinc.com','first_name':'Mary','last_name':'Jane','title':'Software Engineer','sales_info': {'stage':'Customer','lifetime_value':48000,'account_owner':'mary@contoso.com' }, }}update_users_batch([userA,userB],moesif_options)
Themetadata
field can contain any customer demographic or other info you want to store. Moesif only requires theuser_id
field.
For more information, see the function documentation inMoesif Python API Reference.
To update a singlecompany, use theupdate_company()
function.
frommoesif_aws_lambda.middlewareimport*moesif_options= {'LOG_BODY':True,'DEBUG':True,}# Only company_id is required.# Campaign object is optional, but useful if you want to track ROI of acquisition channels# See https://www.moesif.com/docs/api#update-a-company for campaign schema# metadata can be any custom objectcompany= {'company_id':'67890','company_domain':'acmeinc.com',# If domain is set, Moesif will enrich your profiles with publicly available info'campaign': {'utm_source':'google','utm_medium':'cpc','utm_campaign':'adwords','utm_term':'api+tooling','utm_content':'landing' },'metadata': {'org_name':'Acme, Inc','plan_name':'Free','deal_stage':'Lead','mrr':24000,'demographics': {'alexa_ranking':500000,'employee_count':47 }, }}update_company(company,moesif_options)
Themetadata
field can contain any company demographic or other information you want to store. Moesif only requires thecompany_id
field. For more information, see the function documentation inMoesif Python API Reference.
To update a list ofcompanies in one batch, use theupdate_companies_batch()
function.
frommoesif_aws_lambda.middlewareimport*moesif_options= {'LOG_BODY':True,'DEBUG':True,}companyA= {'company_id':'67890','company_domain':'acmeinc.com',# If domain is set, Moesif will enrich your profiles with publicly available info'metadata': {'org_name':'Acme, Inc','plan_name':'Free','deal_stage':'Lead','mrr':24000,'demographics': {'alexa_ranking':500000,'employee_count':47 }, }}companyB= {'company_id':'09876','company_domain':'contoso.com',# If domain is set, Moesif will enrich your profiles with publicly available info'metadata': {'org_name':'Contoso, Inc','plan_name':'Free','deal_stage':'Lead','mrr':48000,'demographics': {'alexa_ranking':500000,'employee_count':53 }, }}update_companies_batch([companyA,companyB],moesif_options)
Themetadata
field can contain any company demographic or other information you want to store. Moesif only requires thecompany_id
field. For more information, see the function documentation inMoesif Python API Reference.
SeeMoesif AWS Lambda Example for Python for an example Lambda function using this middleware.
If you face any issues using this middleware, try thetroubheshooting guidelines. For further assistance, reach out to oursupport team.
Explore other integration options from Moesif inthe Server Integration Options documentation.
About
Moesif AWS Lambda middleware for Python, for API Monitoring, Analytics, and Monetization.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors5
Uh oh!
There was an error while loading.Please reload this page.