Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
user1481793 Avatar asked Jul 26 '12 06:07

user1481793


People also ask

Can Django make API calls?

Yes, if you have a single threaded, single worker Django app and you spend 2 seconds making an http request.

What is API view in Django?

REST framework provides an APIView class, which subclasses Django's View class. APIView classes are different from regular View classes in the following ways: Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances.

Does Django support REST API?

Now, if you want to provide a REST API, the Django REST Framework is the best option. It make easy to expose parts of your application as a REST API.


1 Answers

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.

like image 85
aychedee Avatar answered Sep 19 '22 21:09

aychedee