Is it possible to send a POST request to external API when receiving one?

Viewed 2971

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?

3 Answers

Yes, You can do that using pip install requests. It means your api is working as a proxy.

Example

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.

Using the requests library, You can POST data to an external API

For Example

import requests

request_type = "POST"
data = {"email":"email", "name": "name"}
api_url = "https://external-api.com/api/post/"
response = requests.request(request_type, api_url, data=data)
Related