Search code examples
pythonrestpython-2.7curlpycurl

How would you use a cURL "GET" with a Python based REST API for network programming?


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.


Solution

  • 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.