Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python requests library for API GET request

I am trying to write a Python script that will allow me to accomplish what I normally would by using CURL to perform an API "GET". I have browsed through some questions on here but I am still a bit confused on how to do this; from what I have seen, I can use the "requests" library like this:

URL = requests.get("www.example.com/123")

However, the Curl command I normally run uses authentication as well. Here is an example:

curl -X GET -H 'Authorization: hibnn:11111:77788777YT666:CAL1' 'http://api.example.com/v1.11/user?id=123456

Can I still use the requests library when creating a script to pull this data? Specifically, I would need to be able to pass along the authentication info along with the URL itself.

Update:

Here is what my code looks like:

import requests 
import json

url = ("api.example.com/v1.11/user?id=123456")
header = {"Authorization": "hibnn:11111:77788777YT666:CAL1"} 
response = requests.get(url, headers=header) 
print(response.json)

However, I am getting a response [401] error. I think I am probably doing something wrong with my headers, can anyone help?

like image 241
user7681184 Avatar asked Oct 24 '25 21:10

user7681184


1 Answers

You may pass headers as keyword argument to the get method.

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}

>>> r = requests.get(url, headers=headers)

Reference

like image 81
Avinash Raj Avatar answered Oct 26 '25 12:10

Avinash Raj