# Unable to authenticate admin and check user existence using python

**URL:** <https://community.grafana.com/t/unable-to-authenticate-admin-and-check-user-existence-using-python/118201>\
**Category:** Authentication\
**Tags:** login\
**Created:** [March 29, 2024, 1:12pm UTC](https://community.grafana.com/t/unable-to-authenticate-admin-and-check-user-existence-using-python/118201 "2024-03-29T13:12:57Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![sraghavendra1512](https://avatars.discourse-cdn.com/v4/letter/s/d78d45/32.png) [@sraghavendra1512](https://community.grafana.com/u/sraghavendra1512)\
**Post date:** [March 29, 2024, 1:12pm UTC](https://community.grafana.com/t/unable-to-authenticate-admin-and-check-user-existence-using-python/118201/1 "2024-03-29T13:12:57Z")

</div>

- What Grafana version and what operating system are you using?  
10.4.3

- **What** are you trying to achieve?  
Check the user existence in Grafana using login/email in python scripting

- **How** are you trying to achieve it?  
def authenticate\_admin(admin\_username, admin\_password, grafana\_url):  
login\_url = f"{grafana\_url}/login"  
data = {‘user’: admin\_username, ‘password’: admin\_password}  
response = requests.post(login\_url, data=data)  
if response.status\_code == 200:  
return response.cookies.get(‘grafana\_sess’)  
else:  
print(“Failed to authenticate admin.”)  
return None

def check\_user\_existence(username, grafana\_url, admin\_username, admin\_password):  
session\_cookie = authenticate\_admin(admin\_username, admin\_password, grafana\_url)  
if session\_cookie:  
headers = {‘Cookie’: ‘grafana\_sess=’ + session\_cookie}  
users\_url = f"{grafana\_url}/api/users/search"  
response = requests.get(users\_url, headers=headers, params={‘query’: username})  
if response.status\_code == 200:  
users = response.json()  
for user in users:  
if user[‘login’] == username or user[‘email’].startswith(username):  
return True  
return False

- What happened?  
Failed to authenticate admin.

- What did you **expect** to happen?  
admin login pass, followed by print user existence in Grafana.

- Can you copy/paste the configuration(s) that you are having problems with?  
def authenticate\_admin(admin\_username, admin\_password, grafana\_url):  
login\_url = f"{grafana\_url}/login"  
data = {‘user’: admin\_username, ‘password’: admin\_password}  
response = requests.post(login\_url, data=data)  
if response.status\_code == 200:  
return response.cookies.get(‘grafana\_sess’)  
else:  
print(“Failed to authenticate admin.”)  
return None

def check\_user\_existence(username, grafana\_url, admin\_username, admin\_password):  
session\_cookie = authenticate\_admin(admin\_username, admin\_password, grafana\_url)  
if session\_cookie:  
headers = {‘Cookie’: ‘grafana\_sess=’ + session\_cookie}  
users\_url = f"{grafana\_url}/api/users/search"  
response = requests.get(users\_url, headers=headers, params={‘query’: username})  
if response.status\_code == 200:  
users = response.json()  
for user in users:  
if user[‘login’] == username or user[‘email’].startswith(username):  
return True  
return False  
def main():  
grafana\_url = “[http://localhost:3000](http://localhost:3000)”  
admin\_username = “admin”  
admin\_password = “\*\*\*\*\*\*\*\*\*\*\*\*”

```
# Example usage to check user existence
username = "ABC"
if check_user_existence(username, grafana_url, admin_username, admin_password):
    print(f"User with username '{username}' exists in Grafana.")
else:
    print(f"User with username '{username}' does not exist in Grafana.")

```

if **name** == “ **main** ”:  
main()

- Did you receive any errors in the Grafana UI or in related logs? If so, please tell us **exactly** what they were.

- Did you follow any online instructions? If so, what is the URL?

---

<div class="post-metadata">

**Author:** ![isaqueprofeta](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/isaqueprofeta/32/38142_2.png) [@isaqueprofeta](https://community.grafana.com/u/isaqueprofeta)\
**Post date:** [March 29, 2024, 1:58pm UTC](https://community.grafana.com/t/unable-to-authenticate-admin-and-check-user-existence-using-python/118201/2 "2024-03-29T13:58:40Z")

</div>

Hi @sraghavendra1512.

I think it’s better for you to not use a cookie based auth for Grafana’s API, it’s better to create a [Service Account](https://grafana.com/docs/grafana/latest/administration/service-accounts/) and use the [Service Account Token](https://grafana.com/docs/grafana/latest/developers/http_api/#service-account-token) that returns a Bearer tokent to be used easier on the Authorization Header of your request.

---

<div class="post-metadata">

**Author:** ![sraghavendra1512](https://avatars.discourse-cdn.com/v4/letter/s/d78d45/32.png) [@sraghavendra1512](https://community.grafana.com/u/sraghavendra1512)\
**Post date:** [March 30, 2024, 4:40pm UTC](https://community.grafana.com/t/unable-to-authenticate-admin-and-check-user-existence-using-python/118201/3 "2024-03-30T16:40:25Z")

</div>

Yes @isaqueprofeta you’re right, I used service account token, it works, now there is new challenge, not sure if I can add it here, See I need to grant Editor permission to a team on a folder using service account token, But the script is failing to recognize folder itself? Script below:  
import requests  
import subprocess  
import json

GRAFANA\_URL = “[http://localhost:3000](http://localhost:3000)”  
GRAFANA\_API\_KEY = “\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*”

def run\_curl\_command(command):  
result = subprocess.run(command, shell=True, capture\_output=True, text=True)  
if result.returncode == 0:  
return result.stdout.strip()  
else:  
print(“Error running curl command:”, result.stderr)  
return None

def get\_folder\_id(folder\_name):  
curl\_command = f"curl -X GET -H ‘Authorization: Bearer {GRAFANA\_API\_KEY}’ -H ‘Content-Type: application/json’ ‘{GRAFANA\_URL}/api/search?type=dash-folder&query={folder\_name}’"  
response = run\_curl\_command(curl\_command)  
print(“Folder search response:”, response)  
if response:  
folders = json.loads(response)  
if folders:  
return folders[0][“id”]  
return None

def get\_team\_id(team\_name):  
curl\_command = f"curl -X GET -H ‘Authorization: Bearer {GRAFANA\_API\_KEY}’ -H ‘Content-Type: application/json’ ‘{GRAFANA\_URL}/api/teams/search?name={team\_name}’"  
response = run\_curl\_command(curl\_command)  
print(“Team search response:”, response)  
if response:  
teams = json.loads(response)[“teams”]  
if teams:  
return teams[0][“id”]  
return None

FOLDER\_NAME = “omg\_apple”  
TEAM\_NAME = “omg\_apple”

folder\_id = get\_folder\_id(FOLDER\_NAME)  
team\_id = get\_team\_id(TEAM\_NAME)

if folder\_id and team\_id:  
print(“Folder ID:”, folder\_id)  
print(“Team ID:”, team\_id)

```
request_body = {
    "permission": "Editor",
    "userOrTeamId": team_id,
}

url = f"{GRAFANA_URL}/api/folders/{folder_id}/permissions"
print("URL for granting permission:", url)

response = requests.post(
    url,
    headers={"Authorization": f"Bearer {GRAFANA_API_KEY}"},
    json=request_body,
)

if response.status_code == 200:
    print("Permission granted successfully!")
else:
    print("Failed to grant permission:", response.status_code)

```

else:  
print(“Failed to retrieve folder ID or team ID.”)

Output: Failed to grant permission: 404  
Please help.

---

<div class="post-metadata">

**Author:** ![sraghavendra1512](https://avatars.discourse-cdn.com/v4/letter/s/d78d45/32.png) [@sraghavendra1512](https://community.grafana.com/u/sraghavendra1512)\
**Post date:** [March 31, 2024, 1:14am UTC](https://community.grafana.com/t/unable-to-authenticate-admin-and-check-user-existence-using-python/118201/4 "2024-03-31T01:14:39Z")

</div>

I tried with curl command:  
curl -X POST [http://localhost:3000/api/folders/181/permissions](http://localhost:3000/api/folders/181/permissions)   
-H “Authorization: Bearer SERVICE\_ACCOUNT\_TOKEN”   
-H “Content-Type: application/json”   
-d '{  
“teamId”: 181,  
“role”: “Editor”  
}  
output: {“message”:“folder not found”,“status”:“not-found”}  
But the folder is present, I rechecked in Grafana UI, folder is present with folder Id: 181 but when we are trying with post method to change the permissions using the above command it gives error stating folder not found. Not sure why it is ending with error? What is the correct API endpoint? Please suggest how to rectify this and use in python script.

---

<div class="post-metadata">

**Author:** ![isaqueprofeta](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/isaqueprofeta/32/38142_2.png) [@isaqueprofeta](https://community.grafana.com/u/isaqueprofeta)\
**Post date:** [April 2, 2024, 3:18am UTC](https://community.grafana.com/t/unable-to-authenticate-admin-and-check-user-existence-using-python/118201/5 "2024-04-02T03:18:21Z")

</div>

@sraghavendra1512 glad you get out of where you has stuck at first.

> [@sraghavendra1512](#):
>
> curl -X POST [http://localhost:3000/api/folders/181/permissions](http://localhost:3000/api/folders/181/permissions)  
> -H “Authorization: Bearer SERVICE\_ACCOUNT\_TOKEN”  
> -H “Content-Type: application/json”  
> -d '{  
> “teamId”: 181,  
> “role”: “Editor”  
> }  
> output: {“message”:“folder not found”,“status”:“not-found”}

Two things.

First one, review your teamId: are you sure that both, team and folder got the same ID?

Second one, please pay more attention to the JSON format on the docs… Sometimes the API of GET VS POST are pretty different. In your case, there’s no “role” parameter. You’ll need to specify the “permission” parameter with an index. Since it’s for Editor, the parameter “permission” would get the number 2 that’s for Edit.

More information review it here: [Folder Permissions HTTP API | Grafana documentation](https://grafana.com/docs/grafana/latest/developers/http_api/folder_permissions/)

Hope it helps.

---

<div class="post-metadata">

**Author:** ![amotl](https://sea2.discourse-cdn.com/grafana/user_avatar/community.grafana.com/amotl/32/5891_2.png) [@amotl](https://community.grafana.com/u/amotl)\
**Post date:** [April 7, 2024, 8:54pm UTC](https://community.grafana.com/t/unable-to-authenticate-admin-and-check-user-existence-using-python/118201/6 "2024-04-07T20:54:46Z")

</div>

Dear Raghavendra and Isaque,

if you are looking into accessing Grafana from Python, you may want to give the grafana-client package a chance.

- Announcement  
["grafana-client" - A client library for accessing the Grafana HTTP API, written in Python](https://community.grafana.com/t/grafana-client-a-client-library-for-accessing-the-grafana-http-api-written-in-python/68101)

- Repository  
[GitHub - panodata/grafana-client: Python client library for accessing the Grafana HTTP API.](https://github.com/panodata/grafana-client)

- PyPI  
[grafana-client · PyPI](https://pypi.org/project/grafana-client/)

If you are running into any issues with respect to your use cases, please let us know on the [issue tracker](https://github.com/panodata/grafana-client/issues), so we can improve the library according to your needs.

With kind regards,  
Andreas.

NB: @usman.ahmad: Coming from [[OSS tool] Write Grafana pre-build dashboards in Python - #2 by usman.ahmad](https://community.grafana.com/t/oss-tool-write-grafana-pre-build-dashboards-in-python/91342/2), you may also want to add an item to the Howto section about it, linking to ["grafana-client" - A client library for accessing the Grafana HTTP API, written in Python](https://community.grafana.com/t/grafana-client-a-client-library-for-accessing-the-grafana-http-api-written-in-python/68101)?

NB2: We’ve also just asked you in a PM to remove the “closed” status on this post, so we could continue adding release notes about significant updates, similar to [Use "grafana-wtf" to search through all entities of a Grafana instance - #6 by amotl](https://community.grafana.com/t/use-grafana-wtf-to-search-through-all-entities-of-a-grafana-instance/13828/6). grafana-client 4.0.0 has been released a few days ago, and we would like to share corresponding news with the community. Thanks!
