Articles

Effortlessly generate code that talks to Device42’s RESTful APIs

Let Postman generate code for Device42 API calls in the language of your choice.

Have you been coding for a while now, but never written an application that speaks to an API? Or maybe you’re learning yet another new language, but aren’t yet familiar with the language’s nuances? Worry not!
Postman Generated Code Snippet

Armed with Device42’s API documentation and a copy of the Postman plugin for your favorite platform/browser, you’ll have code that will chat with Device42’s RESTful API in no time. No more wondering if the code you are writing is broken, or if the API call is wrong!

Today, we will cover three common calls, two POST based and one GET based. We’ll get the calls working, and then have Postman generate code for them in the language of our choice. The calls will:

  1. POST: Request Device42 suggest the next available IP address on the network of your choice. (We’ll also use a GET call in the midst of this step to find our subnet_id)

  2. POST: Add a new device (a new CI) to Device42

  3. GET: Retrieve a list of all Racks

 

1. POST – Get the next free IP

The “Get next available” IP API Call in Device42 is very handy when it comes time to deploy a new server instance to your local network or to the cloud alike. Instead of hunting for a spreadsheet that may or may not be up to date, or playing “ping and pray”, Device42 will provide the next free IP and it’s assured that it isn’t in use.

The API endpoint for this call is: https://yourdevice42.com/api/1.0/suggest_ip/ – this endpoint accepts POST.

Full details around this call can be found in Device42’s API Documentation (linked), but the call requires at minimum Basic Auth (your username & PW), a subnet_id, subnet or name parameter. Optionally, a vrf_group or vrf_group_id can be supplied, or an IP can be reserved via reserve_ip. If required parameters are left out, the API replies as such to let us know [also pictured]:

{
"msg": "subnet_id, subnet or name paramater missing.",
"code": 1
}

 

 

Now that we know we need a subnet ID, let’s use a GET call to get a list of all subnets [assuming you don’t already know the subnet_id]. Go ahead and use Postman to make a GET call to https://YOURDEVICE42.com/api/1.0/subnets/ and find the subnet_id of the subnet you are interested in. The subnet_id of the network I’m looking for is 33:

 

Armed with subnet_id=33, lets get the next available IP, and then see how we can use Postman to implement this functionality in Python.

 

By Selecting “code” [pictured below, highlighted] & choosing Python from the dropdown, you are rewarded with the code to implement this call’s functionality in the language of your choosing!:

 

import requests

url = "https://demoinstance.com/api/1.0/suggest_ip"

querystring = {"subnet_id":"33"}

headers = {
    'authorization': "Basic bWF0dGE6czkzbmY4ZDc2",
    'cache-control': "no-cache",
    'postman-token': "0365fab8-a9d0-b330-e68a-79cff8a185ae"
    }

response = requests.request("POST", url, headers=headers, params=querystring)

print(response.text)

 

There’s even a handy “copy to clipboard” function! Paste into your IDE of choice, and enjoy!

 

2. POST – Add a new device

Now that we’ve already done this once, the second time around should go quicker; Postman already has your authentication credentials, and you’re surely beginning to know the ropes. Adding a new device via the API is a key step in automating a build process, so fellow DevOps oriented shops will appreciate this one.

The API endpoint to add a new device is: https://YOURDEVICE42.com/api/1.0/devices/this endpoint expects a POST.

Full details for this call can be found in Device42’s API documentation. Required parameter is name. Optional parameters we will use are manufacturer, hardware [model], is_it_virtual_host, in_service, os, memory, cpucount, cpucore, and macaddress . For more details on any of the optional parameters and a complete list of parameters, consult the linked documentation.

The new device we will add is a physical server; it’s going to be a Virtual Host, and it’s a Dell PowerEdge R630. I already know I’m going to put it into Rack 42, and I’m going to let Device42 choose the best position by setting start_at=auto. Lets add it to Device42!

For parameters, we’ll send:

  1. name = wh-vhost42

  2. hardware = PowerEdge R630

  3. manufacturer = Dell

  4. is_it_virtual_host = yes

  5. in_service = yes

  6. os = VMWare

  7. memory = 256

  8. cpucount = 2

  9. cpucore = 16

  10. macaddress = FF33296FB538


 

Postman showing parameters to POST.  Don’t forget the TRAILING “/” !!!

And the response:

 

The new device is now visible in Device42. Now let’s grab the code to do the same in Java:

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "name=wh-vhost42&is_it_virtual_host=yes&in_service=yes&type=physical&os=VMWare&memory=256&cpucount=2&cpucore=16&macaddress=FF33296FB538&notes=used_postman");
Request request = new Request.Builder()
  .url("https://yourdevice42/api/device/")
  .post(body)
  .addHeader("authorization", "Basic bWF0dGE6czkzbmY4ZDc2")
  .addHeader("content-type", "application/x-www-form-urlencoded")
  .addHeader("cache-control", "no-cache")
  .addHeader("postman-token", "980ae8be-1fe8-f248-d6d6-b023077d52bc")
  .build();

Response response = client.newCall(request).execute();

Thanks PostMan!

 

3. GET – Get a list of all racks!

At this point, this one should feel like riding a bike! OK, maybe not that natural yet – but hopefully you are getting the hang of it!

The endpoint to get all racks is: https://yourdevice42/api/1.0/racks/ – This endpoint is expecting a GET.

It doesn’t really require many parameters, but here is the documentation, for good measure.

The code, in GO:

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "https://demo2.device42.com/api/1.0/racks/"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Add("authorization", "Basic bWF0dGE6czkzbmY4ZDc2")
	req.Header.Add("cache-control", "no-cache")
	req.Header.Add("postman-token", "6f640616-e3b7-a8c8-ac50-ab2cb0615b0a")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}

 

BONUS!

Sometimes it’s handy to know all the devices IN a rack — So why don’t we get that since we just looked up a list of all racks?

The API endpoint to do this is: https://yourdevice42/api/1.0/devices/?rack_id=42 – And the endpoint is expecting a GET.

The only parameter here is your rack <ID>!  So send a request [basic auth required, as always], and you should get the inventory of the rack you chose!

 

To make this happen in NodeJS, it’s as simple as:

var http = require("https");

var options = {
  "method": "GET",
  "hostname": "demo2.device42.com",
  "port": null,
  "path": "/api/1.0/devices/?rack_id=42",
  "headers": {
    "authorization": "Basic bWF0dGE6czkzbmY4ZDc2",
    "cache-control": "no-cache",
    "postman-token": "7db28e01-7adb-fc88-2a34-93ec8e79e5a5"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();

Of course, it’s totally random that this is Rack #42 : )


Have a question? Comment? Did we get something wrong? Let us know! Leave a comment or drop us an e-mail, and of course — Happy API Coding! 🙂

 

Share this post

About the author