I have written API calls according to Grafana's documentation (https://grafana.com/docs/grafana/latest/developers/http_api/dashboard/#gets-the-home-dashboard) but I always end up with a response of 401. For example, just to get a basic GET response for testing with the path /api/dashboards/home, I have done the following:
On the Grafana settings, I have added an api key and set it to admin. I have tried calling the api using curl, Insomnia (like Postman) and via Python. (Replaced api key and grafana url values)
curl:
curl -k -H "Authorization: Bearer <apikey>" https://<grafanaurl>/api/dashboards/home
response:
curl: (6) Could not resolve host: GET
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested. Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>
python:
import json
import requests
server= "https:<grafanaurl>"
url = server + "/api/dashboards/home"
headers = {
"Authorization": "Bearer <apikey>",
"Accept": "application/json",
"Content-Type": "application/json"
}
r = requests.request("GET", url, headers=headers, verify=False)
print(r)
# print(r.json())
response:
<Response [401]>
Insomnia gives the same error message as curl.
Am I doing something wrong? My organization uses LDAP authentication to automatically log us in to Grafana - could this be a reason why this doesn't work? If so, how would I work with this? I want to be able to call Grafana apis from within an application.
Related
I'm trying to make a get request to Azure DevOps.
I have the URL and the Personal_Access_Token. The URL was created following these intructions https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-6.1&tabs=HTTP#definitions , and it is working fine in the browser. It is possible to see the information of the file that I'm targeting.
However, when I execute the request in python:
import requests
headers = {
'Authorization': 'Bearer myPAT',
}
response = requests.get('exampleurl.com/content', headers=headers)
I'm getting the 203 response...
I have also try other options following this link Python requests library how to pass Authorization header with single token without success. Including these headers:
personal_access_token_encoded = base64.b64encode(personal_access_token.encode('utf-8')).decode('utf-8')
headers={'Authorization': 'Basic '+personal_access_token_encoded}
headers={'Authorization': 'Basic '+personal_access_token}
But in both cases still having the same response.
For sure I'm not considering something. What could be missing?
For Azure DevOps API, you need to use Basic Auth instead of Baerear, providing only the PAT token encoded in base64.
Hi error feedback 203 is about your invalid token.
So what is the authorization type of your request call?
For pat headers = {'Authorization': 'Basic pat'}
For bearer token headers = {'Authorization': 'Bearer MYREALLYLONGTOKENIGOT'}
You could put your rest api in postman and click the code button at the right-side bar to overview the rest api into different script.
I need to POST data to an API endpoint using the python requests library with application/json content-type but am getting errors due to the API key having a space in it.
API Key format:
Authorization: Token d6bf96a81a58bf6e99ad1f819b244242797c0c07
Successful curl request:
curl -k -H "Authorization: Token d6bf96a81a58bf6e99ad1f819b244242797c0c07" "https://myurlhere.com/api/status/" --data "status=Good&value=foobar"
Failed Python:
import requests
url="https://myurlhere.com/api/status/"
headers={"Authorization": "Token d6bf96a81a58bf6e99ad1f819b244242797c0c07","content-type":"application/json}
data="status=Good&value=foobar"
requests.post(url, headers=headers, data=data)
The python request returns a 403, additional debugging shows "Authentication details were not provided."
It appears as if the space is causing issues due to being a json object? Is there any clean way to work around this? I must use the application/json type as I use the same program with a lot more code for other api requests which require the application/json type.
I'm tying to get the data from the Cloudhub API which resides on Mulesoft.
I tried to access through postman (With the same Client Credentials - Bearer Authorization) and it's working fine (I can able to get the result with proper get requests).
But when I tried to do the same with Python requests library I ran into issues. Here is my piece of code:
import requests
import json, os
CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
headers = {'Accept': '*/*',
'Cache-Control':'no-cache',
'Accept-Encoding': 'gzip, deflate',
'Content-Type':'application/json, application/x-www-form-urlencoded',
'Connection': 'keep-alive'}
url='https://<domain-name>-api.us-w2.cloudhub.io/api/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET), headers= headers)
token_raw = json.loads(response.text)
print(token_raw)
Result: {'error': 'Authentication denied.'}
All I need to know is
How it's working fine with Postman but why I'm not able to connect with python code?
Is there anything I've to change in my code or any additional information needed for this request? or am I passing the correct endpoint in receiving the access token for Cloudhub API?
Please post your suggestions or any documentation that I need to refer.
Hope the information that I gave is clear and Thanks in Advance !!
I found the answer of my own question. I can get it from the postman itself.
Here is my code for API Call with Python.
import http.client
import os
conn = http.client.HTTPSConnection("<domain-name>-api.us-w2.cloudhub.io")
payload = ''
headers = {
'client_id': os.environ['CLIENT_ID'],
'client_secret': os.environ['CLIENT_SECRET']
}
conn.request("GET", "/api/<Query that you want to pass - endpoint>", payload, headers)
response = conn.getresponse()
resp_data = response.read()
print(resp_data.decode("utf-8"))
The URL is incorrect. To call CloudHub REST API you need to obtain a bearer token from Anypoint Platform REST API. The URL mentioned looks to for some application deployed in CloudHub, not from the platform APIs. This is the same method than to get the bearer token to use in Anypoint MQ Admin API. It looks like you are trying to use the Anypoint MQ Broker API, which is an Anypoint MQ specific token.
Example in Curl to get an Anypoint Platform token:
$ curl -H "Content-Type: application/json" -X POST -d '{"username":"joe.blogs","password":"sample.password"}' https://anypoint.mulesoft.com/accounts/login
{
"access_token": "f648eea2-3704-4560-bb46-bfff79712652",
"token_type": "bearer",
"redirectUrl": "/home/"
}
Additionally the Content-type of your example seems incorrect because it has 2 values.
I'm sure the Postman request is different for it to work, or maybe it works only for the Anypoint MQ Broker API.
I am quite new to Python and was trying to simulate the result captured when testing API POST requests in Postman. I am basically trying to capture the token generated using the Post method.
I have the following details in Postman which gives me the token details.
Authorization Tab: Type: Basic Auth, Username, Password
Headers Tab: Content-Type: application/x-www-form-urlencoded, Authorization: #This is Auto-Filled
Body Tab: raw: grant_type=client_credentials&scope=read_snfa_unifiedgateway
Now when i run with above details in Postman, it gives me access token in the result but when i use the same details using the following Python Code, i get only <Response [200]> as result for response variable.
import requests
url = 'https://appurl.com/oauth/ls/connect/token'
body = 'grant_type=client_credentials&scope=read_snfa_unifiedgateway'
response = requests.post(
url,
body,
auth=HTTPBasicAuth('my_username', 'my_password'), headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
How can i change the above Python code in such a way that i could get the result in the format i get in Postman as following and then i could use the access_token value in next operation for another POST Method?
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbsdfsdfsdfsdfcsdcsdvarglkwelkrmgmasdmnfjtugnasmdfisdfmmmmpeirhg_-e60s72zgV8Gn2hUiWwlelNQhJongUW6fxwD42c1N5u4R2JJdrj5V_bIwnvY_C_l5wHlIFSQRE1E-5KzP7WG9XjmV9oXRXXGjNhwRqEocGdiEMjcibyiYQNZmG2h-GbsTKvCc21hRNhyRF_y4mdwVUytAXT68TuwZxsTbjUzEvPdwd2JZaFnD9Elo7akSk2ROnRMxN70fsoLzEK71kbzoYkti1jX_V8i_s6K0wmLma-x4nc2kW5mpFM0R9NPqH-kGf-4ZUKim03frifpsGl6Nqo-eN5oZ-b6YgK56mSjxpxQ",
"expires_in": 3600,
"token_type": "Bearer"
}
Use response.json() to get result in dict format. You can use
access_token = response.json()['access_token']
I am trying to login into the server via post with my python script, but it is not working although when i am doing the same POST via postman it is working fine. I believe my python script is not saving the authentication cookie information or may be i have to add some more fields in my payload. I am at very very beginner level of programming so please guide me how i can save that authentication cookie which i can further use in my next GET, POST requests.
When i run this POST request via postman. I simply give username and password in the body and i got the following successful response
{
"ErrorCode": 0,
"Data": {
"role": "admin",
"_id": "7c9e7mdf4d249212282480zb",
"name": "test5"
}
}
but when I run below mentioned Python script, I am getting
<!DOCTYPE HTML PUBLIC"-//IETF//DTD HTML 2.0//EN">
500 Internal Server error
Please find below mentioned my python script
import requests
url = "http://172.125.169.21/api/user/login"
payload = "{\"name\": \"test5\", \"password\": \"Hello123\"}"
response = requests.request("POST", url, data=payload)
print(response.text)
print(response.headers)
For the requests library in python, the data object takes a python dict object, not a JSON string. If you were to edit your code to:
import requests
import json
url = "http://172.125.169.21/api/user/login"
payload = {"name": "test5", "password": "Hello123"}
headers = {'Content-Type': "application/json"}
response = requests.request("POST", url, json=payload, headers=headers)
# the json parameter should handle encoding for you
print(response.text)
print(response.headers)
Cookies are available to you in the cookies parameter of the response object. See the requests documentation for more information.
print(json.dumps(response.cookies, separators=(",",":"), indent = 4))
This should pretty print the cookie(s) you've received. You can use requests' session handling abilities or a variable to store this information, however you choose. We'll save these cookies to a requests cookiejar:
cookies = response.cookies
and we'll use those cookies in the authorization check or any other requests:
auth_check_url = "172.125.169.21/api/user/checkLogin"
response = requests.get(auth_check_url, cookies=cookies)
print(response.text)