Function Configuration
- Language: Python
- Image:
python:3.12.1-slim
- Concurrency: Sync
- Environment Variables:
API_KEY
: Your API key for making external requests.
- Packages:
requests
: For making HTTP requests.json
: For parsing JSON responses (included in Python standard library).
Function Code
This function takes a query parameter from the request, makes an external API call using the requests
package, parses the response, and returns a custom error message if something goes wrong. Otherwise, it returns a success message.
import os
import requests
def handler(request):
param_value = request.get('params', {}).get('param_name')
if not param_value:
return {
"statusCode": 400,
"body": "Missing 'param_name' in query parameters."
}
api_key = os.getenv('API_KEY')
api_url = f"https://api.example.com/data?query={param_value}&apiKey={api_key}"
return make_external_request(api_url)
def make_external_request(api_url):
try:
response = requests.get(api_url)
response.raise_for_status()
return {
"statusCode": 200,
"body": response.json()
}
except requests.exceptions.RequestException as e:
return {
"statusCode": 500,
"body": f"External API request failed: {str(e)}"
}
except ValueError as e:
return {
"statusCode": 500,
"body": f"JSON decoding failed: {str(e)}"
}