Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
API & service automationMiddleCommonPerformance

Why does reusing a `requests.Session()` object across multiple calls to the same host improve API test performance?

Answer

A `requests.Session()` keeps an underlying connection pool alive between calls, so repeated requests to the same host reuse an already-established TCP connection (and TLS handshake for HTTPS) instead of paying the full connection-setup cost on every single call. A session also lets you set shared configuration once — headers, authentication, cookies — instead of repeating it on every individual `requests.get(...)` call, which both speeds up a large API test suite and reduces the chance of accidentally sending inconsistent headers across different requests.

Strong answer includes

  • a Session keeps a connection pool alive, reusing TCP/TLS setup across requests
  • avoids paying full connection-setup cost on every single call
  • also centralizes shared config like headers and auth in one place

Practical example

Running 500 API test assertions against the same host with

Python example
session = requests.Session()

reused across them is measurably faster than calling

Python example
requests.get(...)

500 times independently, each opening a fresh connection.

#requests#performance#test-automation

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules