1

I am trying to connect to an API by using the code they have provided in the documentation. However, during the authorization request, I get the TypeError: can't concat str to bytes. I have searched through stack overflow but most of the problems are related to the 'body' instead of the 'params' and 'header' inputs.

My code:

from email import header, message
import requests, http.client, urllib.request, urllib.parse, urllib.error, base64
import json

url = "https://sts.nordpoolgroup.com/connect/token"

payload = "grant_type=password&scope=marketdata_api&username{username}&password={password}"
headers = {
    "accept": "application/json",
    "content-type": "application/x-www-form-urlencoded",
    "Authorization": "Basic {Client Authorization String}"
}

response = requests.post(url, data=payload, headers=headers)
unknown = response.json()['token_type'] +' '+ response.json()['access_token']

headers = {
    # Request headers
    'Accept-Encoding': 'application/json',
    'Authorization': str(unknown),
}

params = urllib.parse.urlencode({
    # Request parameters
    'deliveryareafrom': 'DK1','DK2'
    'deliveryareato': 'DE',
    'startTime': '2022-10-04T00:00:00Z',
    'endTime': '2022-10-05T23:59:59Z',
})

try:
    conn = http.client.HTTPSConnection('marketdata-api.nordpoolgroup.com')
    conn.request("GET", "/dayahead/capacities/offered?%s" % params, headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except OSError as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

Currently, the variable 'headers' is a dict[str, str] type and 'params' is a str. I assume, although not sure, that the problem is related to this. Therefore, I tried to convert the dictionary to string using str(params), json.dumps(params) and str.encode() or bytes.decode()without success. The new error in this case is that b'{ "statusCode": 401, "message": "No Authorization header provided" }'

I have tried to use Postman where the 'params' were obtained from the following URL

https://marketdata-api.nordpoolgroup.com/dayahead/capacities/offered?deliveryareafrom=DK1&deliveryareato=DE&startTime=2022-10-04T00:00:00Z&endTime=2022-10-05T00:00:00Z

and Bearer token from the request response was added to the 'header' tab. It worked fine, so the issue should be with my code.

I am certainly missing something here, just cannot figure out what. I'd appreciate any help since I started coding recently.

Full traceback:

  File "c:\Users\dnc\PycharmProjects\pythonProject\nordpool_api.py", line 34, in <module>
    conn.request("GET", "/dayahead/capacities/offered?%s" % params, headers)
  File "C:\Users\dnc\Anaconda3\envs\pythonProject\lib\http\client.py", line 1282, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\dnc\Anaconda3\envs\pythonProject\lib\http\client.py", line 1328, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "C:\Users\dnc\Anaconda3\envs\pythonProject\lib\http\client.py", line 1277, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "C:\Users\dnc\Anaconda3\envs\pythonProject\lib\http\client.py", line 1074, in _send_output
    chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
TypeError: can't concat str to bytes
csgzdnes
  • 11
  • 2
  • what do you have in ```response.json()['token_type']``` and ```response.json()['access_token']``` ? – svfat Oct 18 '22 at 11:31
  • Can you also post the complete traceback – Abdul Niyas P M Oct 18 '22 at 11:32
  • Bearer (always Bearer) and eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5CdWg4VFhkY0gzOHN0TzNaTjV3MmQtdU8zOCIs.... which should be the token access token (expiring every hour) – csgzdnes Oct 18 '22 at 11:36
  • Can you try `conn.request("GET", "/dayahead/capacities/offered?%s" % params, headers=headers)` – Abdul Niyas P M Oct 18 '22 at 11:50
  • I get the following error: ```b' \r\nBad Request\r\n\r\n

    Bad Request

    \r\n

    HTTP Error 400. The request is badly formed.

    \r\n\r\n'```
    – csgzdnes Oct 18 '22 at 11:52
  • Note that this is invalid syntax: `'deliveryareafrom': 'DK1','DK2'`. It's actually creating a key named `"DK2deliveryareato"` in this case which is probably *not* what you want. – mousetail Oct 19 '22 at 07:52
  • I tried to run it without the second parameter such as ```'deliveryareafrom': 'DK1',``` but HTTP Error 400 still persists. – csgzdnes Oct 19 '22 at 10:43

0 Answers0