user7552123
user7552123

Reputation:

Callback URL for the API Response Django

I am building a code editor using the Hackerearth API.I have made the code to send a asynchronous API Request as it would speed up performance and reduce waiting time.

I referred their docs about sending an async request.I need to specify a callback url.Currently my project is running locally.So I couldn't figure out how to specify the callback URL and render out the Response from that callback URL.The logic to process the response received at the callback url is also specified in their docs.

def compileCode(request):
    if request.is_ajax():
        source = request.POST.get('source')
        lang = request.POST.get('lang')
        client_secret = settings.CLIENT_SECRET
        data = {
           "client_secret": client_secret,
           "async": 1,
           'id': 123,        
           'callback': **what to do here**,
           "source": source,
           "lang": lang,
        }
        res = requests.post(RUN_URL, data=data)
        return JsonResponse(res.json(), safe=False)        
    return HttpResponseBadRequest()

Code to process the Response from the callback URL

def api_response(request):
   payload = request.POST.get('payload', '')
   payload = json.loads(payload)
   run_status = payload.get('run_status')
   o = run_status['output']
   return HttpResponse('API Response Recieved!')

Any help is welcome :)

Upvotes: 2

Views: 4807

Answers (1)

Astik Anand
Astik Anand

Reputation: 13047

A callback URL "calls back" a web address rather than a bit of code and it can be invoked by API method, you can call after it's done. That URL can be anything. It doesn't have to be a static URL. Often it is a script to perform certain functions.

As here you don't need to perform anything after receiving results.

You don't need to pass the callback url, it will work even without it.

I made it work by just passing by below code.

RUN_URL = "https://api.hackerearth.com/v3/code/run/"
CLIENT_SECRET = 'your-client-secret-from-hackerearth'

data = {
    'client_secret': CLIENT_SECRET,
    'async': 1,
    'source': source,
    'lang': lang,
}

r = requests.post(RUN_URL, data=data)

Upvotes: 0

Related Questions