Hit API Gateway for IAM authentication. Create SigV4 signature header (python)

Run API Gateway for IAM authentication (python)

When you want to return the API result with curl etc., it is necessary to calculate the header (SigV4 signature) of the HTTP request, but note that the material is not found See other sites for how to make API Gateway IAM authenticated. There is a way to calculate the hash value, but I'm not sure, so when I need it, I look inside the botocore library and create it.

check_iam.py


import os
from botocore.awsrequest import AWSRequest
from botocore.auth import SigV4Auth
from botocore.endpoint import URLLib3Session
from botocore.credentials import Credentials
import requests

url_ = "https://xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com/v1"
### 1.Credential generation
credentials = Credentials(os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_ACCESS_KEY'])

### 2.AWS Request generation
request = AWSRequest(method="GET", url=url_)

### 3.AWS request signature
SigV4Auth(credentials, 'execute-api', ap-northeast-1).add_auth(request)

### 4.API issuance
headers = {
    'Authorization': request.headers['Authorization'],
    'Host':'xxxxxxxxxx.execute-api.ap-northeast-1.amazonaws.com',
    'X-Amz-Date':request.context['timestamp']
}

response = requests.get(url_,headers=headers)

print(response.text)

Recommended Posts

Hit API Gateway for IAM authentication. Create SigV4 signature header (python)
Create API with Python, lambda, API Gateway quickly using AWS SAM
Hit Mastodon's API in Python
AWS CDK-Lambda + API Gateway (Python)
Try IAM Database Authentication from Python
Create Awaitable with Python / C API
[AWS] Create API with API Gateway + Lambda
Hit the Sesami API in Python
[Python] Hit the Google Translation API
Hit the Etherpad-lite API with Python
Create Gmail in Python without API
Hit the web API in Python
[Python] Create API to send Gmail