Unirest (only available for Python2)
Installing & Making a Request
To use Unirest for Python, install it using pip:
$ pip install unirest
After installing the pip package, you can now begin making API requests by importing unirest and forming a request:
import unirest
response = unirest.post(API_URL,
headers={
"X-RapidAPI-Key": API_KEY,
"Content-Type": "application/x-www-form-urlencoded"
},
params={
"parameter": "value"
}
)
response.code # The HTTP status code
response.headers # The HTTP headers
response.body # The parsed response
response.raw_body # The unparsed response
Asynchronous Requests
Python also supports asynchronous requests in which you can define a callback function to be passed along and invoked when Unirest receives the response:
def callback_function(response):
response.code # The HTTP status code
response.headers # The HTTP headers
response.body # The parsed response
response.raw_body # The unparsed response
thread = unirest.post(API_URL, headers={"X-RapidAPI-Key": API_KEY,"Content-Type": "application/x-www-form-urlencoded"}, params={"parameter": "value"}, callback=callback_function)
File Uploads
Transferring file data requires that you open the file in a readable r mode:
import unirest
response = unirest.post(API_URL,
headers={
"X-RapidAPI-Key": API_KEY,
"Accept": "application/json"
},
params={
"parameter": "value",
"file": open("/tmp/file", mode="r")
}
)
response.code # The HTTP status code
response.headers # The HTTP headers
response.body # The parsed response
response.raw_body # The unparsed response
Unirest Functionality
The available methods
Advanced Configuration
You can set some advanced configuration to tune Unirest-Python:
Timeout
You can set a custom timeout value (in seconds):
unirest.timeout(5) # 5s timeout
Default Request Headers
You can set default headers that will be sent on every request:
unirest.default_header('Header1','Value1')
unirest.default_header('Header2','Value2')
You can clear the default headers anytime with:
unirest.clear_default_headers()
Learn more about how to use an API with Python.
Updated about 3 years ago