Pre- request Scripts
Pre-request script is a piece of code that will run before the execution of a request. Pre-request scripts gives users a chance to modify the request after variables have been resolved but before the request is made.
Example- Generating signatures for authentication
Pre-Request Script of Python
Pre-processing tasks including setting parameters, variable values, body data and headers can be performed using the pre-request script. Pre-request scripts can also be used to debug the code, for example, by logging output to the console. Additionally, we may obtain the result of the function, such as the date, time, timestamp, etc., utilising the pre-request script notion.
The code that is run prior to sending an HTTP request using an application like requests is known as the "pre-request" script in Python. Before submitting the actual request, the pre-request script is used to change the response fields or headers.
Below are the various examples of Pre-Request Scripts
Amazon SP API
Method - POST
import time
import datetime, hashlib, hmac
import json
access_key='{{access_key}}' # Provide Values
secret_key='{{secret_key}}' # Provide Values
host = '{{host}}' # Provide Values
endpoint = '{{hostname}}' # Provide Values
canonical_uri = '{{canonical_uri}}' # Provide Values
body = {{body}} # Provide Values
##########################################################################################################################################################
request_parameters =json.dumps(body)
t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d')
method = 'POST'
service = 'execute-api'
region = 'us-east-1'
canonical_querystring = ''
canonical_headers = 'host:' + host + '\\n' + 'x-amz-date:' + amzdate + '\\n'
signed_headers = 'host;x-amz-date'
payload_hash = hashlib.sha256((request_parameters).encode('utf-8')).hexdigest()
canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/'+ service + '/' + 'aws4_request'
string_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()
kDate = hmac.new(('AWS4' + secret_key).encode('utf-8'), datestamp.encode('utf-8'), hashlib.sha256).digest()
kRegion = hmac.new(kDate, region.encode('utf-8'), hashlib.sha256).digest()
kService = hmac.new(kRegion, service.encode('utf-8'), hashlib.sha256).digest()
kSigning = hmac.new(kService, 'aws4_request'.encode('utf-8'), hashlib.sha256).digest()
signing_key = kSigning
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature