0

I ran my codes below but get a response of "Error: 401 Status Code: 401; Unauthorized"

def Pods_Assets(token):
    url = "https://api.aqmeshdata.net/api/Pods/Assets_V1"

    # Implement Bearer authentication
    class BearerAuth(requests.auth.AuthBase):
        def __init__(self, bearer_token):
            self.token = bearer_token
    
        def __call__(self, r):
            r.headers['Authorization'] = 'Bearer ' + self.token
            return r
    
    api_token = {"authorization": token}
    
    auth = BearerAuth(api_token["authorization"])
    
    headers = {"Accept": "application/json"}
    
    # Make the GET request
    response = requests.get(url, auth=auth, headers=headers)
    
    if response.status_code == 200:
        json_response = response.json()
        data: object = json_response
        print('Successfully retrieve data: [site_details]')
        print('Response time:', response.elapsed.total_seconds(), 'seconds', '\n')
        return data
    else:
        print("Error:", response.status_code, response.text)

I tried to use POST Requests Online tools to figure out the website is still working properly. The raw is listed below.

GET /api/Pods/Assets_V1 HTTP/1.1
Authorization: Bearer  xxxxx
Host: api.aqmeshdata.net
Accept: application/json

The supplier provided me an example file. The content is listed below.

        "request": {
            "auth": {
                "type": "bearer",
                "bearer": [
                    {
                        "key": "token",
                        "value": "{{SampleAuthToken}}",
                        "type": "string"
                    }
                ]
            },
            "method": "GET",
            "header": [
                {
                    "key": "Accept",
                    "value": "application/xml",
                    "disabled": true
                },
                {
                    "key": "Accept",
                    "value": "application/json",
                    "disabled": true
                }
            ],
            "url": {
                "raw": "https://api.aqmeshdata.net/api/Pods/Assets",
                "protocol": "https",
                "host": [
                    "api",
                    "aqmeshdata",
                    "net"
                ],
                "path": [
                    "api",
                    "Pods",
                    "Assets"
                ]
            }
        },
2
  • Your code looks reasonable albeit that the use of a custom auth class seems unnecessary in this case. Best guess is that what you think is a valid bearer token is not actually valid
    – SIGHUP
    Commented Jun 24 at 14:11
  • I don't understand why you create BearerAuth? Why not use values directly in headers. You may also send request to httpbin.org/get and it will send you back all your headers and data - and you will see if code sends correct headers.
    – furas
    Commented Jun 24 at 14:40

1 Answer 1

0

Change the bearer code to your code and run.

Let me know.

import requests
import os

root_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(root_path)

def get_json_data (url, headers, params=None, payload=None):
    try:
        response = requests.get(url, headers=headers, params=params, data=payload)
        response.raise_for_status()
        if response.status_code == 200:
            return response.json()
        else:
            return None
    except Exception as e:
        print(f"Request Error: {e}")
        return None
    
def main():
    
    apiurl = 'https://api.aqmeshdata.net/api/Pods/Assets_V'
    bearer_token = ''

    headers = {
        'Accept': 'application/json',
        'Host' : 'api.aqmeshdata.net',
        'Authorization': 'Bearer ' + bearer_token,
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
    }

    response = get_json_data(apiurl, headers)
    print(response)
    
if __name__ == "__main__":
    main()

Not the answer you're looking for? Browse other questions tagged or ask your own question.