简体   繁体   中英

Calling a REST API from django view

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

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 .

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')
 ## 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM