Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

How Do I Pass JSON in header of Python Script?

First of all, let me say that I've never done Python before. I want to know how I can pass JSON
{  
  "data": {
    "attributes": {
      "url": "https://www.example.com",      
      "subscriptions": [        
          "rule.created"      
      ]    
   }  
 } 
}

Open in new window

Into the header of my script. Here is the test script (I didn't write it and I have removed sensitive data, keys etc.)
#To install Requirements, use: pip3 install -r requirements.txt
#Documentation: https://developer.adobelaunch.com/api/

import json
import time
import jwt
import datetime
import os
from datetime import datetime, timedelta, timezone, date
import requests
import csv
import sys

# BOTW Account

org_id = ""
tech_id = ""
api_key = ""
secret = ""
company_id = ""
key_path = ""
property_id = ""

def createJWT():

   expiryTime = int(time.time()) + 300

   data = {
      "exp": expiryTime,
      "iss": org_id,
      "sub": tech_id,
      "https://ims-na1.adobelogin.com/s/ent_reactor_sdk": True,
      "aud": "https://ims-na1.adobelogin.com/c/" + api_key
   }
 
   with open(key_path,"rb") as readFile:
      privateKey = readFile.read()
 
   encoded = jwt.encode(data, privateKey, algorithm="RS256")
   #print('encoded: ', encoded)
   return encoded

#print("createJWT: ", createJWT())

def accessToken():

   encoded = createJWT()
   #print("encoded: ", encoded)
   #encoded = "eyJhbGciOiJSUzI1NiJ9"
   exchangeEndpoint = "https://ims-na1.adobelogin.com/ims/exchange/jwt"
   header_jwt = {'cache-control':'no-cache','content-type':'application/x-www-form-urlencoded'} ## setting the header

   exchangeData = {
      "client_id": api_key,
      "client_secret": secret,
      "jwt_token": encoded,
      'x-api-key': api_key,
       'x-gw-ims-org-id': org_id
   }

   #print("exchangeData: ", json.dumps(exchangeData, indent=4, sort_keys=True))

   exchangeResponse = requests.post(exchangeEndpoint, headers=header_jwt, data=exchangeData)

   #print("exchangeResponse: ", exchangeResponse.text)

   token = exchangeResponse.json()['access_token']
   #token = exchangeResponse.json()
   

   #token = "eyJhbGciOiJS"

   #print("token: ", json.dumps(token, indent=4, sort_keys=True))
   return token

def checkKey(dict, key): 
      
    if key in dict.keys(): 
        return True
    else: 
        return False 


def apiConn(url):
   token = accessToken()
   #print('token: ', token)
   #token = token['accessToken']
   #print("bearer Token: ", token)

   
   #header_jwt = {'cache-control':'no-cache','content-type':'application/x-www-form-urlencoded'} ## setting the header

   # create payload
   header_jwt = {
       'authorization' : 'Bearer ' + token,
       'Accept' : 'application/vnd.api+json;revision=1',
       'Content-Type': 'application/vnd.api+json',
       'x-api-key': api_key,
       'x-gw-ims-org-id': org_id
   }
   #print('url: ', url)
   response = requests.get(url, headers=header_jwt)
   #print('response: ',    response)
   apiResponse = response.json()
   
   return apiResponse

#url = "https://reactor.adobe.io/properties/" + property_id + "/rules"
url = "https://reactor.adobe.io/properties/" + property_id + "/callbacks"
#print('url: ', url)

apiResponse = apiConn(url)
print('apiResponse', json.dumps(apiResponse,indent=4, sort_keys=True))
print('Processing Complete')

Open in new window


Thanks!

Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

It is not clear what you mean by "pass"

Include from external file?
Ajax from a browser  - for example a form submission?
Grabbed from another URL?

If it is a configuration file, have a look here

https://www.loekvandenouweland.com/content/using-json-config-files-in-python.html

import json

with open('config.json') as config_file:
file = json.load(config_file)

data = file['data']

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

FYI... the JSON will be included in the initial file. It is just for testing purposes. I'll take a look and see if I can follow what everyone is suggesting! Thanks!
Avatar of MJ

ASKER

Hi,
This appeared to work. I know I didn't get an error. Not getting the response in webhook though? I removed my webhooks URL for safety here!?!?

def apiConn(url):
   token = accessToken()
   #print('token: ', token)
   #token = token['accessToken']
   #print("bearer Token: ", token)

   
   #header_jwt = {'cache-control':'no-cache','content-type':'application/x-www-form-urlencoded'} ## setting the header

   # create payload
   header_jwt = {
       'authorization' : 'Bearer ' + token,
       'Accept' : 'application/vnd.api+json;revision=1',
       'Content-Type': 'application/vnd.api+json',
       'x-api-key': api_key,
       'x-gw-ims-org-id': org_id
   }
   #print('url: ', url)
   
   data = {
      "attributes": {
         "url": "https://webhook.site/...",
         "subscriptions": [
            "rule.created"
         ]
      }
   }
   
   
   #response = requests.get(url, headers=header_jwt)
   response = requests.get(url, data=json.dumps(data), headers=header_jwt)
   #print('response: ',    response)
   apiResponse = response.json()
   
   return apiResponse

Open in new window