pythonhttprequest

Return multiple values from HTTP response


I am trying to create a property map in "Authentik" which fetches values from other services. in this case I need to use an API key to return 3 values from a request to an Emby Server. At first I tried with curl to see if I am able to get a response:

curl 'http://myserver:80/backend?api_key=xyz' -H 'Content-Type: application/json; charset=UTF-8' --data-raw '{[my request data]}' --compressed

The returned data containes the values I require: "AccessToken", "ServerId" and "Id". Now I am trying to do the same with Python. The goal is to end up with something like thins:

{
    "ak_proxy": {
        "user_attributes": {
            "additionalHeaders": {
                "X-Emby-Token": "[value from response data]",
                "X-Emby-ServerId": "[value from response data]",
                "X-Emby-Id": "[value from response data]"
            }
        }
    }
}

with this in mind, I wrote the following:

import json
from urllib.parse import urlencode
from urllib.request import Request, urlopen

base_url = "http://myserver:80"
end_point = "/backend?api_key=xyz"
json_data = {[my request data]}
postdata = json.dumps(json_data).encode()
headers = {"Content-Type": "application/json; charset=UTF-8"}
try:
  httprequest = Request(base_url + end_point, data=postdata, method="POST", headers=headers)
  with urlopen(httprequest) as response:
    responddata = json.loads(response.read().decode())
  return {"ak_proxy": {"user_attributes": {"additionalHeaders": {"X-server-Token": responddata['AccessToken'], "X-server-ServerId": responddata['ServerId'], "X-server-Id": responddata['Id']}}}}
except: return "null"

I get:

SyntaxError: 'return' outside function

when testing the Python code.


Solution

  • Thank You ! It helped me debug and finde the issue. I did as @Justinas said:

    try:
      httprequest = Request(base_url + end_point, data=postdata, method="POST", headers=headers)
      with urlopen(httprequest) as response:
        responddata = json.loads(response.read().decode())
      AccessToken = responddata['AccessToken']
      ServerId = responddata['ServerId']
      UserId = responddata['User']['Id']
    except:
      AccessToken = "null"
      ServerId = "null"
      UserId = "null"
    
    return {"ak_proxy": {"user_attributes": {"additionalHeaders": {"X-Emby-Token": AccessToken, "X-Emby-ServerId": ServerId, "X-Emby-UserId": UserId}}}}
    

    I seperated each output and the issue was with the Value of ID. JSON Data is an array and the value if ID is part of User.