0

I'm writing a simple test script and for some reason, I get two different results after calling the same GET request and using the same syntax. This is what I get when using the wrong syntax (NOT using headers=...) for two different APIs:

>> import requests
>> head1 = { 'key' : 'API-key1' }
>> url1 = 'https://url1.com'
>> r1 = requests.get(url1, head1)     ## Notice headers=head1 wasn't used
>> print(r1)
<Response [200]>                      ## Yet a valid response prints out
>> print(r1.json())
{'response': 'valid response'}


>> head2 = { 'key' : 'API-key2' }
>> url2 = 'https://url2.com'
>> r2 = requests.get(url2, head2)     ## But in this instance
>> print(r2)
<Response [401]>
>> print(r2.json())                   ## I get an 401 error
<bound method Response.json of <Response [401]>>

Similarly, if I use the correct syntax for both, this is what I get

>> import requests
>> head1 = { 'key' : 'API-key1' }
>> url1 = 'https://url1.com'
>> r1 = requests.get(url1, headers=head1)   ## Using the correct syntax
>> print(r1)
<Response [200]>
>> print(r1.json())                         ## But it received an error
{'response': {'error': [{'msg': 'No API access key supplied'}]}}



>> head2 = { 'key' : 'API-key2' }
>> url2 = 'https://url2.com'
>> r2 = requests.get(url2, headers=head2)   ## This works
>> print(r2)
<Response [200]>
>> print(r2.json())
{'response': 'valid response'}

Is this an issue with the API I'm using for the first request? How come the first GET request with one API take in incorrect syntax for headers, but with correct syntax, it responds with a successful GET but says that it didn't take in the API key I put in the header? The second API looks like it works properly, though, which is confusing.

janielle
  • 1
  • 1

1 Answers1

0

Here is how requests.get is defined:

def get(url, params=None, **kwargs):

Notice how there's one required argument url, followed by one keyword argument params and then the general **kwarg. So when you pass requests.get(url1, head1), the head1 is being passed as the params kwarg, not as headers. This is why when you pass it by explicitly stating the name, it works.

Note that the first way isn't incorrect syntax, there is a difference between keyword, positional, and required arguments, with some overlap. This answer explains it better

Charchit Agarwal
  • 2,829
  • 2
  • 8
  • 20