How to filter requests that are coming to a Rest Endpoint in Python

Assume that your actual Rest API gets a number of identical hits, but actually that Rest Endpoint expects only one hit in order to proceed with the rest of the work!

How to handle this?

In Python, we can handle the scenario by developing a proxy.

Assume that our actual API resides at ‘http://localhost:6001/response’

But we need to send only one request to this API, but actually it getting hit by 100 calls. In order to avoid this, we can make this simple trick.

Create another API as below and count the number of hits.

@app.route('/proxy', methods=['POST'])
def proxy():
with counter.get_lock():
counter.value += 1
unique_count = counter.value

url = 'http://localhost:6001/response'
if unique_count == 1:
data = request.get_json(), json=data)

return jsonify({'Response': 'OK'}), 200

It needs to import the following.

from multiprocessing import Value

Create a variable in the beginning of the program.

counter = Value('i', 0)

Then all the requests can be redirected to the http://localhost:<port>/proxy. It will exactly redirect one request to the actual endpoint.