Quick Intro to Python Requests Library
Calling 3rd party services is an essential part of web development these days. I did a quick little python article on Basic urllib GET
and POST
With and Without Data. It was a good look into how python natively handles doing GET
and POST
HTTP actions. However, there is a better way, and that is with the requests library.
GET
Most of what you will be doing is using different HTTP Verbs. GET
is probably the one you will use the most, and it is simple to do. Look at the following code example:
import requests
r = requests.get('https://localhost/user/buddylindsey/')
print(r.text)
print(r.json())
You can even pass in some data with your get request.
import requests
r = requests.get(
'https://localhost/user/',
params={'user':'buddy'}
)
This builds up the request and adds the data as a query-string automagically. Makes things a bit easier don’t you think?
POST
import requests
r = request.post(
'http://localhost/user/new',
{'username':'buddylindsey', 'password':'password'}
)
print(r.status_code)
print(r.json())
Other Verbs
OPTIONS
, HEAD
, PUT
, PATCH
and DELETE
are also available. To be honest I haven’t used OPTIONS
, PATCH
, or HEAD
before so while I have a basic understanding of how they work I won’t attempt to explain it to you. Instead please visit the requests HTTP verbs docs to get a better understanding of their usage.
More on Response Object
The great thing about the response object you get back after making a request is you all of the options available for things to do and know. Here are some of the methods and properties you have access to:
- headers
- status_code
- text
- json()
- encoding
There are many more, but these are probably the ones you will use the most.
Conclusion
The requests library is one of the best, if not the best, libraries for calling 3rd party web services and acting upon them. This is a powerful tool to have in your toolbelt, it is recommended to learn it, and learn it well.