Python


Installing & Making a Request

To use Unirest for Python, install it using pip:

Shell
$ pip install unirest

After installing the pip package, you can now begin making API requests by importing unirest and forming a request:

Python
import unirest

response = unirest.post(API_URL,
  headers={
    "X-Mashape-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:

Python
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-Mashape-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:

Python
import unirest

response = unirest.post(API_URL,
  headers={
    "X-Mashape-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):

Python
unirest.timeout(5) # 5s timeout
Default Request Headers

You can set default headers that will be sent on every request:

Python
unirest.default_header('Header1','Value1')
unirest.default_header('Header2','Value2')

You can clear the default headers anytime with:

Python
unirest.clear_default_headers()