25

Is there any way to make a RESTful api call from django view?

I am trying to pass header and parameters along a url from the django views. I am googling from half an hour but could not find anything interesting.

Any help would be appreciated

Francisco Puga
  • 23,869
  • 5
  • 48
  • 64
user1481793
  • 543
  • 2
  • 13
  • 21
  • Welcome to Stack Overflow! We encourage you to [research your questions](http://stackoverflow.com/questions/how-to-ask). If you've [tried something already](http://whathaveyoutried.com/), please add it to the question - if not, research and attempt your question first, and then come back. –  Jul 26 '12 at 06:52
  • 3
    Then you should have considered it when asking your question. –  Jul 26 '12 at 06:54

3 Answers3

44

Yes of course there is. You could use urllib2.urlopen but I prefer requests.

import requests

def my_django_view(request):
    if request.method == 'POST':
        r = requests.post('https://www.somedomain.com/some/url/save', params=request.POST)
    else:
        r = requests.get('https://www.somedomain.com/some/url/save', params=request.GET)
    if r.status_code == 200:
        return HttpResponse('Yay, it worked')
    return HttpResponse('Could not save data')

The requests library is a very simple API over the top of urllib3, everything you need to know about making a request using it can be found here.

Sahir Saiyed
  • 518
  • 8
  • 17
aychedee
  • 24,871
  • 8
  • 79
  • 83
  • And what about headers and parameters? :) –  Jul 26 '12 at 07:24
  • 1
    Sheesh, I'll get there eventually :-) I'll leave the headers for the questioner to 'work out' themselves. Headers are in request.META. You don't want to just blindly pass the whole thing along. The keyword arg for requests is 'headers', so you could do request(headers=request.META), but it would seem a bit screwy since request length and stuff like that are in the headers. – aychedee Jul 26 '12 at 07:32
  • The question is basic but any comments regarding if this is a good practice ? For instance, if the consumed API is unreliable and you need to setup retries, won't that potentially stall the entire django application ? – Overdrivr Oct 17 '18 at 07:53
  • The answer is: It depends! Yes, if you have a single threaded, single worker Django app and you spend 2 seconds making an http request. Other incoming requests will queue up and maybe fail. However, making an http request doesn't typically use that many resources. CPU wise. So maybe you use threaded requests and you can handle thousands of these per second. Or maybe you create the view in nginx and let that proxy the endpoint you're trying to consume. I've done something similar to the above before, in a production app. And I've also worked around this in other different ways. – aychedee Oct 17 '18 at 12:39
  • I am calling my API endpoint using this method but when I use params in requests.post method the endpoint just get stuck and if I use data in the method I am not receiving anything in the request of my endpoint please help me through this. – RIO Mar 14 '23 at 03:57
2

Yes i am posting my source code it may help you

import requests
def my_django_view(request):
    url = "https://test"
    header = {
    "Content-Type":"application/json",
    "X-Client-Id":"6786787678f7dd8we77e787",
    "X-Client-Secret":"96777676767585",
    }
    payload = {   
    "subscriptionId" :"3456745",
    "planId" : "check",
    "returnUrl": "https://www.linkedin.com/in/itsharshyadav/" 
    }
    result = requests.post(url,  data=json.dumps(payload), headers=header)
    if result.status_code == 200:
        return HttpResponse('Successful')
    return HttpResponse('Something went wrong')

In case of Get API

import requests

def my_django_view(request):
    url = "https://test"
    header = {
    "Content-Type":"application/json",
    "X-Client-Id":"6786787678f7dd8we77e787",
    "X-Client-Secret":"96777676767585",
    }
    
    result = requests.get(url,headers=header)
    if result.status_code == 200:
        return HttpResponse('Successful')
    return HttpResponse('Something went wrong')
0
 ## POST Data To Django Server using python script ##  
   def sendDataToServer(server_url, people_count,store_id, brand_id, time_slot, footfall_time):
        try:
            result = requests.post(url="url", data={"people_count": people_count, "store_id": store_id, "brand_id": brand_id,"time_slot": time_slot, "footfall_time": footfall_time})
            print(result)
            lJsonResult = result.json()
            if lJsonResult['ResponseCode'] == 200:
                print("Data Send")
                info("Data Sent to the server successfully: ")
    
        except Exception as e:
            print("Failed to send json to server....", e)