简体   繁体   中英

Postman AWS Rest API — as javascript?

I made a simple IAM authenticated API that returns a random number. [GET only]
Postman call works ok:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html?shortFooter=true

What is a simple way of getting the postman call to plain javascript
(No npm or webpack)

Thanks heaps

You can use axios and aws4 library in javascript to make api calls and send a signed request respectively.You need to authenticate the user via Cognito and retrieve temporary credentials (access key, secret key, and session token)

let request = {
  host: 'myapi.execute-api.us-west-2.amazonaws.com',
  method: 'GET',
  url: 'https://myapi.execute-api.us-west-2.amazonaws.com/foo/bar',
  path: '/foo/bar'
}

let signedRequest = aws4.sign(request,
  {
    // assumes user has authenticated and we have called
    // AWS.config.credentials.get to retrieve keys and
    // session tokens
    secretAccessKey: AWS.config.credentials.secretAccessKey,
    accessKeyId: AWS.config.credentials.accessKeyId,
    sessionToken: AWS.config.credentials.sessionToken
  })

delete signedRequest.headers['Host']
delete signedRequest.headers['Content-Length']

let response = await axios(signedRequest)

This article might help you with the basic code to get temporary credentials from cognito and authenticate the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM