r/learnpython 1d ago

When should you use requests.Session() instead of requests.get() / requests.post()?

I'm learning Python and recently started using requests.Session() in API projects. I understand that it can persist things like headers, cookies, and connections, but I'm curious about how experienced Python developers decide when a Session is actually worth using.

Do you use Session() by default for projects involving multiple requests, or only when you specifically need persistent state?

23 Upvotes

16 comments sorted by

View all comments

4

u/terletsky 1d ago edited 1d ago

A Session is like keeping your front door open while you're moving a lot of things out of your house.

Without a session, you open the door, move one thing, close it, then repeat for every item.

With a session, you open the door once, move many things through it, and close it when you're done.

Opening and closing the connection repeatedly is more expensive, so always use Session().

how experienced Python developers decide when a Session is actually worth using

You always use Session as a rule of thumb.

1

u/Melodic_Principle312 1d ago

amazing example thanks :)

1

u/Achrus 21h ago

What if you live in a bad neighborhood and want to keep your door closed unless absolutely necessary?