4

Let me begin by saying I am a novice with cURL, Python and REST.

Here's what I'm trying to do:

I have a virtual network with an SDN controller (Contrail). Contrail has a Python based REST API to allow for network automation development and management.

To access this REST API I have been trying to use cURL scripts temporarily through a Firefox extension, "RESTClient" just to make sure the cURL calls work independently from Python.

The cURL scripts are intended to query the VNs (virtual networks) and print out their information so that I can input IDs of the specific VNs that I need to remove as part of maintenance.

Here are the cURL scripts I'm currently working with:

Request:

curl -X GET -H "Content-Type: application/json; charset=UTF-8" http://10.xx.xx.xx:1234/virtual-networks

Response (without values):

{"virtual-networks": [{"href": , "fq_name": , ["default-domain", "vn-blue"], "uuid"}

.

Essentially, I want to be able to run the cURL script above in Python. I have Python 2.7, urllib2, libcurl, and pycurl set up, I just can't figure out the right syntax.

leafsca
  • 65
  • 1
  • 5

2 Answers2

4

If you can install the requests library, you can use:

response = requests.get('http://10.xx.xx.xx:1234/virtual-networks')
response.json

You can set the header of the request with:

headers = {'content-type': 'application/json'}
response = requests.get('http://10.xx.xx.xx:1234/virtual-networks', headers=headers)

However you should only define Content-type for POST, PUT, PATCH requests, and use Acceptfor a GET.

2

Essentially, you want to craft a special HTTP request using urllib2, or -- some might consider this much better -- the 3rd party requests module. A HTTP request is not a too complex thing, you first might want to read about HTTP requests in general (start at Wikipedia or even look at the newly released RFC 723*)). In your curl invocation, you are setting certain header parameters (using the -H switch). You can easily reproduce these using request's custom headers function, documented here: http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers.

Community
  • 1
  • 1
Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130