Fire and forget API calls using requests in Python

If you are using the requests library in python for making API calls, there may be cases where you’d just like to fire and forget the call, i.e., not wait for the response. This is especially true if your API is time-consuming and the response doesn’t really matter and triggering the API call is all that counts.

A simple hack to get this done is to use the timeout argument of the requests.get() or requests.post() functions. Of course, that will generate a ReadTimeout error if the API doesn’t return a response within the timeout, but that can easily be handled by a try-except block.

Thus, instead of

import requests

def myfunc():
  #Tasks before API call
  requests.post(url='https://iotespresso.com', data=data)
  #Tasks after API call

Your code changes to:

import requests

def myfunc():
  #Tasks before API call
  try:
    requests.post(url=url, data=data,timeout=1) #1sec timeout
  except: 
    pass
  #Tasks after API call

In this way, the tasks .after the API call can start executing as soon as the timeout (1 second in the above example) is reached.

Please note that you should NOT use this hack when the response of the API is important to you and is required for further processing. This should be used only in cases where making the API call is all that matters. An example would be triggering an AWS Lambda function, which can then independently execute in the background, once it is triggered.

You can read more about the timeout argument of requests’ functions here. I hope you found this tutorial helpful.

If you wish to learn how to create REST APIs with flask and python, you can check out this course on Udemy.

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *