[Django]-Calling a REST API from django view

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.

πŸ‘€aychedee

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')
πŸ‘€Harsh Yadav

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)

Leave a comment