Created
October 14, 2016 21:52
-
-
Save iSkore/b22b6ce6d8bcd714643d46f9e1c7c5a1 to your computer and use it in GitHub Desktop.
Example of how to make a request to AWS's API using raw HTTP request in Node.JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
let crypto = require( 'crypto' ), | |
request = require( 'request' ), | |
qstr = require( 'querystring' ), | |
keys = Object.keys, | |
signString = ( method, endpoint, uri, qs ) => `${method}\n${endpoint}\n${uri}\n${qs}`, | |
makeString = ( ...args ) => args.join( '' ), | |
generateHmac = ( signedData, awsSecretKey ) => crypto.createHmac( 'sha256', awsSecretKey ).update( signedData ).digest( 'base64' ), | |
urlEncode = o => keys( o ).reduce( ( r, k ) => ( r[ encodeURIComponent( k ) ] = encodeURIComponent( o[ k ] ), r ), {} ), | |
sortObject = o => keys( o ).sort().reduce( ( r, k ) => ( r[ k ] = o[ k ], r ), {} ); | |
const | |
ts = new Date(), | |
AWSKeys = { | |
kAccess: 'AWS_ACCESS_KEY', | |
kSecret: 'AWS_SECRET_KEY' | |
}, | |
options = { | |
method: 'GET', | |
url: 'webservices.amazon.com', | |
path: '/onca/xml', | |
qs: { | |
Service: 'AWSECommerceService', | |
Operation: 'ItemSearch', | |
AWSAccessKeyId: AWSKeys.kAccess, | |
AssociateTag: 'tag-20', | |
SearchIndex: 'Appliances', | |
Keywords: 'games', | |
ResponseGroup: 'SalesRank', | |
Sort: 'salesrank', | |
Timestamp: ts.toISOString().split( '.' )[ 0 ] + '.000Z' | |
} | |
}; | |
function makeRequest( opt ) { | |
let qstring = opt.qs, signed, reqURL; | |
qstring = sortObject( qstring ); | |
qstring = qstr.stringify( qstring ); | |
signed = '&Signature=' + generateHmac( signString( opt.method, opt.url, opt.path, qstring ), AWSKeys.kSecret ); | |
qstring += signed; | |
console.log( qstring ); | |
reqURL = makeString( 'http://', opt.url, opt.path, '?', qstring ); | |
console.log( reqURL ); | |
request( reqURL, ( error, response, body ) => { | |
if ( !error && response.statusCode === 200 ) { | |
console.log( body ); | |
} else { | |
console.log( body ); | |
} | |
} ); | |
} | |
makeRequest( options ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment