I'm receiving a JSON POST request from my frontend and store it in my database - this is standard behavior of my backend.
Is it possible to send the same data (or some parts of it, after validation) with another POST request to an external API that is not managed by me? If so, I think it would be by extending create method - am I correct? How could I trigger sending a request to that 3rd Party API on receiving it in my backend?
Do you know any examples?
Yes, You can do that using pip install requests. It means your api is working as a proxy.
from rest_framework import Response
import requests
def api_view(request):
external_api_url = 'https://example.com/api/endpoint/'
data = request.POST
res = requests.post(external_api_url, data)
return Response(res.json())
You can create (override) your custom "create" view method, adding the call to the external API (if the external API is REST, "request" is a good tool).
Establish a new HTTP conections (external) can penalize the endpoint response speed, and if the external service is too slow, can produce timeout so I suggest do the external api call using async mechanism, (celery task worker or async functions) and ensure with a retrive loop and timeout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With