Rest API [python requests]: connection


I’m trying connecting to calponia’s API from script:

  • with curl
curl -v --request POST \
  -H "Content-Type: application/json" \
  --url \
  --data '{ "query": { "": {"_eq": "<PROJECT_ID>"}}, "limit": 5}' \
  --header "Authorization: Token ${TOKEN}"

$TOKEN is set as environment variable. So good, so far it works. I shortened the log:

> POST /v2/devices/search HTTP/2
> Host:
> user-agent: curl/7.68.0
> accept: */*
> content-type: application/json
> authorization: Token <$TOKEN>
> content-length: 88
* We are completely uploaded and fine
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
* Connection state changed (MAX_CONCURRENT_STREAMS == 4294967295)!
< HTTP/2 200

Now trying with Python’s requests:


TOKEN = environ.get("TOKEN")
PROJECT_ID = environ.get("PROJECT_ID")

class CalponiaAuth(AuthBase):
    """Attaches Token to header for a given Request object."""

    def __init__(self, token: str):
        self.token = token

    def __call__(self, req: requests.PreparedRequest):
        # modify and return the request
        req.headers["Authorization"] = f"Token {self.token}"
        return req

    def __str__(self):
        return f"Authorization: Token {self.token}"

# Make a requests Session, setting TOKEN in headers and SSL certificates
with requests.Session() as session:
    session.verify = "/etc/rb-trustcenter/Bosch-CA-bundle.cert.pem"
    session.auth = CalponiaAuth(TOKEN)

    # Simple API call
        "query": {"": {"_eq": f"{PROJECT_ID}"}}, 
        "limit": 5,
    req: requests.Response ="{BASE_URL}/devices/search", json=POST_REQUEST)

The token seems to be correctly set (<$TOKEN> is set set to the correct token value):

DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1):
DEBUG:urllib3.connectionpool: "GET /v2/info HTTP/1.1" 200 90
Using calponia version v0.7.0-c (commit 7e8ae97) on
DEBUG:http.client:send: b'POST /v2/devices/search HTTP/1.1\r\nHost:\r\nUser-Agent: curl/7.68.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\nContent-Length: 86\r\nContent-Type: application/json\r\nAuthorization: Token <$TOKEN>\r\n\r\n'
DEBUG:http.client:send: b'{"query": {"": {"_eq": "d7699400-72b1-11eb-838b-ffb19ab3f944"}}, "limit": 5}'
DEBUG:http.client:reply: 'HTTP/1.1 401 Unauthorized\r\n'

Used a similar go script and same 401 error. Any idea on what I’m doing wrong?

Hi @emmanuel.roux,

did you use the same token for both calls?

The curl-command sends to, while the python-script is using So this must be a different token.

1 Like

Hello @thomas.schuerle

thanks for noticing the url point, that solved indeed the issue.