How to consume Django Rest Framework with a simple python application

时间:2017-04-10 02:51:54

标签: python django django-rest-framework

I need to make a python app to make a connection with the API

The python app is gonna send the user's ID to the API, then it's gonna get some informations about this user, such as their name, whether they are authenticated and so on.

I already know how to create the rest api, But I don't know how to consume it.

Thanks.

1 个答案:

答案 0 :(得分:6)

You can use requests. Use it like this:

# Get 
resp = requests.get('https://api.github.com/user', auth=('user', 'pass'))
json_response = resp.json()
# Response: {u'private_gists': 419, u'total_private_repos': 77, ...}
is_authenticated = json_response.get('is_authenticated', False)
if is_authenticated == True:
   # Do stuff

# Post
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
r.json()
# Similar response as above