# How could I pull Loki records from a Python script?

**URL:** <https://community.grafana.com/t/how-could-i-pull-loki-records-from-a-python-script/111483>\
**Category:** Grafana Loki\
**Created:** [January 8, 2024, 1:05pm UTC](https://community.grafana.com/t/how-could-i-pull-loki-records-from-a-python-script/111483 "2024-01-08T13:05:52Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![ralvez](https://avatars.discourse-cdn.com/v4/letter/r/a6a055/32.png) [@ralvez](https://community.grafana.com/u/ralvez)\
**Post date:** [January 9, 2024, 5:25pm UTC](https://community.grafana.com/t/how-could-i-pull-loki-records-from-a-python-script/111483/4 "2024-01-09T17:25:34Z")

</div>

I am not so proud of my piece of code, but the following gave me access to the Loki records 🙂

The following is the payload that will be used as argument of the POST message to Grafana to ask it for the Loki records:

def payload(switch):  
argument = {  
“queries”: [  
{  
“refId”: “A”,  
“key”: “Q-f03bc30a-9f33-45a4-8fd0-9d9c3662b890-0”,  
“datasource”: {  
“type”: “loki”,  
“uid”: “JKn0-PDSk”  
},  
“editorMode”: “builder”,  
“expr”: “{hostname="”+switch+“", loglevel="5"} |= `changed state to`”,  
“queryType”: “range”,  
“maxLines”: Loki\_lines\_to\_retrieve,  
“legendFormat”: “”,  
“datasourceId”: 22,  
“intervalMs”: 15000,  
“maxDataPoints”: 1485  
}  
],  
“from”: “2024-01-08T00:00:00.000Z”,  
“to”: “2024-01-08T23:59:59.000Z”,  
}  
return(argument)

The following are the other arguments of the POST:

apikey=‘\<JKKJHJKKLLLJKJLLHUJNK;BJ \>’

headers = {‘Authorization’: apikey,‘Accept’: ‘aplication/json’,‘Content-Type’: ‘application/json’}

url=‘[http://admin:admin1@10.235.2.19:3000/api/ds/query](http://admin:admin1@10.235.2.19:3000/api/ds/query)’

And then the following is the POST executed to gather the actual records:

```
PLD=payload(str(LANswitch[0]))
response= requests.post(url, data=json.dumps(PLD),headers=headers)

```

Once I have the answer from Grafana, I iterate on the results (provided that the POST returned a 200 OK). the following lines are executed in a loop:  
while index \>= 0:  
LOG=response.json()[‘results’][‘A’][‘frames’][0][‘data’][‘values’][2][index]  
TIMESTAMP=int(response.json()[‘results’][‘A’][‘frames’][0][‘data’][‘values’][1][index])  
Filtered=LOG.split(“Interface “,1)[1]  
INT=Filtered.split(”,”,1)[0]  
STATE=Filtered.split(“state to “,1)[1].replace(”\n”,‘’)  
(… more lines follow but not shown here…)

It worked quite well, although I would have liked a library like the one I use to ask InfluxDB for its records…

Thanks!!!

---

_[View the full topic](https://community.grafana.com/t/how-could-i-pull-loki-records-from-a-python-script/111483)._
