HTTP / RESTful API Calls with Python Requests Library

Posted on Updated on

The objective of this post is to give a brief introduction to HTTP and RESTful APIs.  Also develop an RESTful client in Python using the “requests” library and “json” library.  I intentionally did not use the urllib2 or any other standard Python library,  since I want to explain the power of the “requests” library, which is a simple and straight forward library for developing RESTful Clients.


HTTP is a request / response protocol and is similar to client-server model.  In the internet world, generally the web browser sends the HTTP request and the web server responds with HTTP response.  Also it is not necessary that the client is always a browser.  The client can be any application which can send a HTTP request.

We have used so many application level communication protocols.  Starting from RPC (Remote Procedure Call), Java RMI (Remote Method Invocation), XML/RPC, SOAP/HTTP.  In this lineage RESTful API is the current application level client-server protocol.

RESTful API is an application level protocol.  It is heavily used in internet (WWW)  and distributed systems.  It is recommended by Services Oriented Architecture (SOA) to communicate between loosely coupled distributed components. The RESTful API is a form of HTTP protocol is the de facto standard for Cloud communications.

The two properties of RESTful which makes suitable for modern internet and cloud communication is stateless and cache-less.  The protocol does not enforce any state-machine, it means there is no order of protocol messages enforced.  Also the protocol will not remember any information across requests or responses.  Each and every request is unique and it has no relation with previous or next request which may come.  To understand more on HTTP protocol look at the references below.  Hence forth we will move along with Python Requests library to learn and develop RESTful API.

Request Library

The Requests python library is simple and straight forward library for developing RESTful Clients.  Python has a built in library called urllib2, it is bit complex and old style when compared to Requests. After writing couple of programs using the urllib2, I am completely convinced by the below statement issued by the developers of Requests.   Also refer the Reference[4] for comparing the code segments written using urllib2 and requests library.

Python’s standard urllib2 module provides most of the HTTP capabilities you need, but the API is thoroughly broken. It was built for a different time — and a different web. It requires an enormous amount of work (even method overrides) to perform the simplest of tasks.

Please refer the URL to install the requests library before proceeding.

 The Structure of HTTP / RESTful API

Following are points to remember while developing RESTful API:

  1. URL ( Universal Resource Locator )
  2. Message Type
  3. Headers
  4. Parameters
  5. Payload
  6. Authentication

1. URL

The URL is the core of RESTful API.  Generally the URL refers a web page, but it can also refer a service or a resource.

For example :{photo-id}

The above URL is a resource which holds the photo with id photo-id.  As per the above syntax the value for the photo-id must be replaced with {photo-id}.

Python code snippet to store a URL in a Python object:

>>> url = ''

2. Message Types

HTTP supports GET/POST/PUT/DELETE message types.  There are few more types as well.  Please take a look at the reference[1] to understand them in detail.

GET – to retrieve resource.  Eg. GET will retrieve the photograph stored in that location.

>>> import requests
>>> ret = requests.get(url)
>>> ret.staus_code

POST – to update a resource .  POST will update the existing photo with the new photograph supplied in the message payload.  POST will also create resource, if the resource is not available.

>>> import requests
>>> ret =
>>> ret.status_code

PUT – to create a resource.  PUT will create a resource by uploading the photograph sent on the message payload.

>>> import requests
>>> ret = requests.put(url)
>>> ret.status_code

DELETE – to delete a resource – DELETE will delete the photograph present in that location.

>>> import requests
>>> ret = requests.delete(url)
>>> ret.status_code

 3. Headers

The HTTP header generally contains information used to process the request and responses.  The headers are colon separated key value pairs. For example “Accept: text/plain”.  The http request & response may be have multiple headers.  Since it is a key value pair, we can use Python’s dictionary data type to store these values.

Single Header & Multiple headers:

>>> head = {"Content-type": "application/json"}
>>> head= {"Accept":"applicaiton/json",
        "Content-type": "application/json"}

Make the API call with the above header:

>>> ret = requests.get(url,headers=head)
>>> ret.status_code

In the above statement, “headers” is the name of argument.  So we have used the Python feature of passing named arguments to a function.

4 Parameters

Sometimes we may want to pass values in the URL parameters.  For example, the URL Leader .  This URL expects the user to send the value for the keyword “name” and  “designation”.    The below code snippet helps to you accomplish this tasks.  The “params” argument is used to set the value for parameters.

>>> parameters = {'name':'Saravanan',
          'designation':'Technical Leader'}
>>> head = {'Content-Type':'application/json'}
>>> ret =,params=parameters,header=head)
>>> ret.status_code

5 Payload

The payload contains the data to be sent on the requests.  In this we will see how to send a JSON object in the payload.

empObj = {'name':'Saravanan', 'title':'Architect','Org':'Cisco Systems'}

As in the previous examples, we cannot send the JSON object which is a dictionary data type in Python.  In the above snippet we created a empObj which is a dictionary data type of Python.  This must be converted into JSON object before send the request.

The json library in Python helps here .

>>> import json
>>> emp = json.dumps(empObj)

The json.dumps converts the dictionary object into a JSON object.

The complete code snippet is below:

>>> import json
>>> import requests
>>> url='
>>> head = {'Content-type':'application/json',
>>> payload = {'name':'Saravanan',
               'Orgnization':'Cisco Systems'}

>>> payld = json.dumps(payload)
>>> ret =,header=head,data=payld)
>>> ret.status_code


6 Authorization

The “requests” library supports various forms of authentication, which includes Basic, Digest Authentication, OAuth and others.  The value for authentication can be passed using “auth” parameter of the requests method.

>>> from requests.auth import HTTPBasicAuth
>>> url = ''
>>> requests.get(url, auth=HTTPBasicAuth('username','password')

The “auth” argument can take any function, so if you want to define your own custom authentication and pass it to “auth“.


The above code snippet is a sample to explain the simplicity of Python and requests library.  You can take a look at the official website of Requests and learn advanced concepts in RESTful API developments.




[1] HTTP Wiki :

[2] History of HTTP by W3 Org :

[3] Requests –

[4] Requests and Urllib2 Comparison :

[5] Installation of Requests library :

[6] HTTP Headers –






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s