python requests-cache example

Python Requests Cache Example

If you are working with the Python Requests library, you may want to cache your HTTP requests to improve performance or reduce API call limits. Here is an example of how to use the requests-cache library to achieve this.


You can install requests-cache using pip:

pip install requests-cache


Once you have installed requests-cache, you can use it in your Python code like this:

import requests_cache

# Enable cache

# Make a request
response = requests.get('')

# Check if response was cached

This example installs a cache named 'example_cache' and makes a GET request to ''. The response.from_cache property is True if the response was retrieved from cache.

Cache Options

You can customize the cache by passing options to install_cache(). For example:

    expire_after=3600,  # Cache for one hour
    allowable_methods=('GET', 'POST')  # Only cache GET and POST requests

See the requests-cache documentation for more options.

Another way to use requests-cache is as a context manager:

import requests
import requests_cache

# Enable cache for this block of code
with requests_cache.enabled():
    response1 = requests.get('')
    response2 = requests.get('')

# Cache is disabled outside of the block
response3 = requests.get('')

With this approach, the cache is only enabled for the code inside the with block.


Using requests-cache can greatly improve performance and reduce API call limits when working with the Python Requests library. Try it out in your own projects!