3

I am using python request to fetch data from an API

The API I am using gives this in their documentation:

response = session.get(url, params=parameters)

But the tutorial I read uses:

tes = requests.get(url, headers={'Accept': 'application/json'}, params={'term': 'cat', 'limit': 1})

What is the difference and what should I use?

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29
Ging
  • 29
  • 1
  • 2

1 Answers1

3

Use requests.get() if you only want to fetch a single Item, don't need to login first and don't need cookies to be persistent.

The documentation at requests.readthedocs.io says:

[requests.get() does not have] some of the advantages of having a Requests Session object. In particular, Session-level state such as cookies will not get applied to your request.

You can still send and receive cookies with requests.get() but you would need to manage them yourself.


Use Session.get() if you have a more complex task that requires persistent cookies. Or you want to speed up multiple requests to the same host.

The documentation at requests.readthedocs.io says

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3’s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29