# RACKCORP REST API

# RACKCORP REST API

Rackcorp has migrated many of its functionalities to work with REST API architecture to modernize and make easy the process to get data through HTTP protocol. Every month we are adding new services through REST API. It is important you follow us to get the last updates and the last version of our API.

##### **API Information:**

Current Version: v2.8

API URL: [https://www.rackcorp.net/api/v2.8](https://www.rackcorp.net/api/v2.7)

Before you start to create any code or connect through our API, you need to create an API Key access which allows your code to make HTTPS requests to our services and be authorized to get data for your services. We will explain here how you add this API Key in your code.

To create API credentials, goto ADMINISTRATION -&gt; API in our portal. URL: [https://portal.rackcorp.com/index.php?cmd=api](https://portal.rackcorp.com/index.php?cmd=api&if=0)

Then, you click ADD, type a <span style="text-decoration: underline; color: rgb(224, 62, 45);">**name**</span> for this new Key and a <span style="text-decoration: underline; color: rgb(224, 62, 45);">**secret** </span>( password ) and SAVE.[![key.PNG](https://wiki.rackcorp.com/uploads/images/gallery/2023-01/scaled-1680-/nBxn0uJWbaY6xGpx-key.PNG)](https://wiki.rackcorp.com/uploads/images/gallery/2023-01/nBxn0uJWbaY6xGpx-key.PNG)

<p class="callout warning">Make sure to record your SECRET phrase somewhere safe. It is required for API access and cannot be retrieved, It can only reset via the API portal key details page  
</p>

#####   


##### **API Standards:**

As described in our article [REST API Architecture and Standards](https://wiki.rackcorp.com/books/help-and-support-en/page/rest-api-architecture-and-standards), there is no definitive standard patterns that all engineers/devs should follow to create REST API for their app. In Rackcorp we keep things simple. The main structure for our REST API follows the patterns below:

version: v2.8

main URL: [https://api.rackcorp.net/api](https://api.rackcorp.net/api)

object data: customers | dc | network | api | dns | device

URL format: <span style="color: #3598db;">[https://api.rackcorp.net/api/](https://api.rackcorp.net/api)+version+/object data/+ID item</span>

Example GET all data: [<span style="color: #3598db;">https://api.rackcorp.net/api/v2.8/device</span>](https://api.rackcorp.net/api/v2.7/devices)

Example GET one Item: [<span style="color: #3598db;">https://api.rackcorp.net/api/v2.8/device/1</span> ](https://api.rackcorp.net/api/v2.7/devices/1)

**Bellow is some example code which you can use as example to implement your first REST API connection to our platform:**

<p class="callout warning"><span style="color: #e03e2d;">**We strongly recommend that you only make REST API calls from your back-end code. Be careful when using javascript code to call a REST API url. Never add your credentials in front-end code. Speak to our team if unsure.** </span></p>

In this simple introduction to code REST API, we will use PHP and PYTHON programming language.

**PHP:**

In the sample bellow we add a dummy API KEY and API SECRET. Please, change this data accordingly with your data

```
<?php
// Simple example to get a list of all datacenters
$version = 'v2.8';
$url = "https://api.rackcorp.net/api/". $version . "/dc";
$query = ["cmd"=>"dc.getall"];
$query['APIUUID'] = "";  // No authetnication required for getting datacenter list
$query['APISECRET'] = "";


$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($curl);

if($response) {
	return json_decode($response, true);
}

return false;
?>
```

**PYTHON:**

```
import json
import logging
import sys
import os
import glob
import re
from bson import json_util
from flask.helpers import make_response
from flask import request, jsonify

version = 'v2.8'
apiurl = 'https://api.rackcorp.net/api'+version+'/'+dc
setheaders = {
        'content-type': 'application/json',
        'User-Agent': 'Mozilla',
        'jwt': jwt
}

data = {}
data['APIUUID'] = ''
data['APISECRET'] = ''

apiresp = None
apiresp = requests.get(self.apiurl+'/sessions/logout',data=self.rcdata,headers=setheaders)
```

As you can see in both examples, the logic to connect through our API is quite simple. You just need the URL, the APIUUID and APISECRET as part of the object or array that gets passed to the API.

Below you can find links with more advanced docs to use our API. Also, the complete list of REST API services (urls) explaining the query data and the expected response data for each situation.

##### **REST API GibHub Docs:**

[Link:<span style="color: #3598db;"> https://github.com/RackCorpCloud/rackcorp-api/wiki/RACKCORP-REST-API</span>](https://github.com/RackCorpCloud/rackcorp-api/wiki/RACKCORP-REST-API)

##### **Swagger RACKCORP REST API:**

Swagger is a suite of API developer tools from SmartBear Software and a former specification upon which the OpenAPI Specification is based. This platform displays in simple layout all REST API functions allowing you visualize what your code should expect as response for each call (GET, PUT, PUSH, DELETE).

You can see through this platform the schema for each function and also, the expected JSON format response. You can also make tests to connect through your services in our servers using your real APIUUID and APISECRET.

It is good for testing staging environments and make sure that your call will receive exactly what your code expects.

<p class="callout info">Dont forget to select which url path API you wanna use for tests. In Swagger page you can see in Server three options. The first one is a swagger mocking URL which is not for tests. The second one is the RACKCORP Production REST API Core (please be careful to use this URL ). The third one is the RACKCORP Staging REST API which should be used for tests.</p>

Link: [https://app.swaggerhub.com/apis/RackCorp/Rackcorp-REST-API/2.8](https://app.swaggerhub.com/apis/RackCorp/Rackcorp-REST-API/2.8 "https://app.swaggerhub.com/apis/RackCorp/Rackcorp-REST-API/2.8")[ ](https://app.swaggerhub.com/apis/RackCorp/Rackcorp-REST-API/2.7)

# RACKCORP REST API EXAMPLES

**Reference material:**

**Swagger App: [https://app.swaggerhub.com/apis-docs/RackCorp/Rackcorp-REST-API/2.8](https://app.swaggerhub.com/apis-docs/RackCorp/Rackcorp-REST-API/2.8)**

**Rackcorp REST API docs: [https://wiki.rackcorp.com/books/help-and-support-en/page/rest-api-architecture-and-standards](https://wiki.rackcorp.com/books/help-and-support-en/page/rest-api-architecture-and-standards "https://wiki.rackcorp.com/books/help-and-support-en/page/rest-api-architecture-and-standards")**

**PHP Code:**

**Simple server creation:**

```
<?php

// IMPORTANT - as described in our documentation, Rackcorp follows the REST API standards 
and each function must be requested with the correct METHOD (GET, POST, PUT, DELETE). 
Pay attention to this detail when create your code to use CURL

function rackcorpAPI($action, $request) {
		$URL = 'https://api.rackcorp.net/api/v2.8'+$action;
        $request["APIUUID"] = "";
        $request["APISECRET"] = "";

        $curl = curl_init($URL);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($request));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        if ( !$response ) {
                return Array("code" => "FAULT", "message" => "API Error");
        }
        return json_decode($response, true);
}

$customerID = 1000;  // Change this to your customer ID (available in portal under ADMINISTRATION -> MY DETAILS)
// locations are defined here: https://wiki.rackcorp.com/books/help-and-support-en/page/rackcorp-datacenter-locations-and-codes

$neworder = "data": [
    "customerid": $customerID,
    "currency": "AUD",
    "servicebilltag": "CLOUDSERVER",
    "productdetails": [
      "BILLINGMODEL": "monthly",
      "NOINSTANCES": 1,
      "HOSTNAME": "Test Machine",
      "CLOUDTYPE": "public",
      "DCID": "89",
      "OS": "OS-ALMALINUX-16.1",
      "VMHID": "",
      "CPU": 2,
      "MEMORYGB": 4,
      "STORAGEGB": 20,
      "IPV6": 0,
      "IPV4": 1,
      "NT-SPEED": "NT-SPEED100",
      "TRAFFICGB": "TRAFFICGB-100",
      "BKP": "BKP-FREE",
      "SUPPORT": "SUPPORT-STD",
      "DDOS": "",
      "SECURITY":[]
    ]
  ];
// Lodge the order (this just locks pricing in for up to 72 hours but doesnt actually create any resources)
// IMPORTANT - method POST
$response = rackcorpAPI("/order/create/server", $neworder);
var_dump($response);

// You can look up the order if you want:
// IMPORTANT - method GET
$response = rackcorpAPI("/order/"+$response['data']["orderid"]);
var_dump($response);

// Then confirm the order to start provisioning:
// IMPORTANT - method GET
$response = rackcorpAPI("/order/confirm/server/"+$response['data']["orderid"]);
var_dump($response);

?>
```

**Starting a server using cloud-init:**

After creating a server, you can also choose to start it using cloud-init with your own custom code:

```
$cloudInitStartupData = Array(
        "cloudInit" => Array(
                "volumeName" => "config-2",
                "userData" => "#cloud-config
ssh_pwauth: True
users:
  - default
  - name: user1
    groups: sudo
    shell: /bin/bash
    sudo: ['ALL=(ALL) NOPASSWD:ALL']
    plain_text_passwd: testtest888
    lock_passwd: false
",
                "metaData" => "instance-id: ServerTest9999
local-hostname: MyServerHostname9999
"
        )
);
$serverIDToStart = 9999;
$tx = Array ("objId"=>$serverIDToStart, "objType"=>"DEVICE", "type"=>"STARTUP", "data"=>json_encode($cloudInitStartupData));

// See earlier example for rackcorpAPI function
$response = rackcorpAPI("rctransaction.create", $tx);
var_dump($response);
?>
```

# REST API Architecture and Standards

REST API architecture has been create to make the procedures to access data from different services easier and more standardized.

This logical architecture frequently uses json data structure to send and receive data. JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays.

Json data example:

```
{ <br></br>	"api": "v2.7",<br></br>    "apipath": "https://www.rackcorp.net/api/v2.7"<br></br>    }
```

This data could be represented as an array or object in many languages such as PHP, PYTHON and C#

Rackcorp has migrated many of its functionalities to work with REST API architecture to modernize and make easy the process to get data through HTTP protocol. Every month we are adding new services through REST API. It is important you follow us to get the last updates and the last version of our API.

##### **Some important concept of REST API:**

- **HTTP methods - GET, POST, PUT, DELETE**

Web developers are likely familiar with GET and POST, along with the other HTTP methods, also sometimes called HTTP verbs. These methods define the type of request being made to a REST API.

- **Methods by use:**
    - GET - request data
    - POST - insert new data
    - PUT - update data
    - DELETE - delete data

- **Resource Names:**

Resources are sometimes referred to as the nouns that the HTTP verbs act upon. Earlier web services were built around remote procedure calls, which saw APIs as extensions of the code that called them. By contrast, REST resources can be accessed with multiple HTTP methods.

- - `GET /api/animals:` retrieve a list of animals
    - `POST /api/animals:` add a new animal
    - `GET /api/animals/dog:` retrieve a single animal by ID
    - `PUT /api/animals/dog:` update a single animal by ID
    - `DELETE /api/animals/dog:` delete an animal by ID

- **Data Formats:**

Most API requests will return content from the server that the client needs to interpret. Rarely is this content plain text—usually, it will use a structured data format. While REST does not specify any data formats, JSON and XML are the two most commonly used.

Json:

```
{<br></br>  "id": "dog",<br></br>  "name": "Pet dog",<br></br>  "genus": "Canis",<br></br>  "img": "https://cdn2.thedogapi.com/images/1MZ0YbOpS.jpg"<br></br>}
```

Xml:

```
<?xml version="1.0" encoding="UTF-8" ?><br></br><root><br></br>  <id>dog</id><br></br>  <name>Domestic dog</name><br></br>  <genus>Canis</genus><br></br>  <img>https://cdn2.thedogapi.com/images/1MZ0YbOpS.jpg<br></br></img><br></br></root>
```

- **HTTP Statuses:**

Since REST APIs depend upon HTTP standards, each request’s status is used to communicate the result of the request, such as success or failure. Each status code provides a machine-readable response, plus a human-readable message. Web developers (and a number of users) will be familiar with many of these.

- - **200**: Success
    - **201**: Created
    - **401**: Unauthorized
    - **403**: Forbidden
    - **404**: Not found
    - **429**: Too many requests

While REST is not a standard, there are many other standards often associated with REST. For example, OAuth covers third-party authorization for resources while JSON PATCH describes a standard approach to the HTTP PATCH method for the JSON data format. An important standard to keep in mind as you design your own APIs is the OpenAPI specification.

##### **How to make a REST API request to get, insert and update data?**

You can make a REST API using any programming language such as Javascript, PHP, PYTHON and C#. In this article we will add some samples of code to explain how to make a request using Javascript (JQUERY) and PHP. We choose these two languages because it is most popular language to deploy a website.

<p class="callout warning"><span style="color: #e03e2d;">**We strongly recommend only make REST API calls from your back-end code, be careful when use javascript code to call a REST API url. Never add your credentials in front-end code.**</span></p>

**Javscript (JQUERY):**

Firstly, you need to create a small logic to call the api url as the sample bellow:

```
<script><br></br>let query = {};<br></br>const v = 'v2.7';<br></br>const URL = 'https://www.rackcorp.net/api/'+v+'/dcs';<br></br>$.ajax({<br></br>	ur: URL,<br></br>    type: 'GET',<br></br>    data: query,<br></br>    success: function(res) {<br></br>        console.log(res);<br></br>        alert(res);<br></br>    },<br></br>    error: function(res) {<br></br>    	console.log(res);<br></br>        alert(res);<br></br>    }<br></br>});<br></br></script><br></br>    
```

You can see that the code to make requests using REST API is quite simple.

We have a variable called 'data' which is the object which would contain the pair of key-values which will be translate into a query in back-end. Them, we create a string variable which is the URL to connect to the REST API HTTP. With this two variables, we are able to create the AJAX script to call the REST API. If the code is correct, the logic will redirect to SUCCESS, if the code is wrong it will redirect to ERROR. Them, you can treat the response ('rest') as you wish.

Be careful to use javascript to make REST API requests. It is because javascript is a front-end programming language, it means the code runs in the user desktop (notebook, phones) and this code can be intercepted by hackers and any other malicious person. REST API requests in javascript is only recommended when you dont need to pass sensitive data, like keys, password or personal information. In the sample above, we called an URL to list all Data Centers (DC) in Rackcorp which doesnt need authentication, it is open to the world.

**PHP:**

In PHP usually developers use CURL function to connect through HTTP. In the sample bellow you can understand how to implement a REST API request from your server to another server.

```
<?php<br></br><br></br>$v = 'v2.7';<br></br>$url = "https://api.rackcorp.net/api/". $v . "/dcs";<br></br>$query = [];<br></br><br></br>$curl = curl_init($url);<br></br>curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));<br></br>curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);<br></br><br></br>$response = curl_exec($curl);<br></br><br></br>if($response) {<br></br>	return json_decode($response, true);<br></br>}<br></br><br></br>return false;
```

As you can see we created the same variables 'v' and 'query' in PHP to call the REST API url. Them, we start creating the CURL initial command. We set some options in the CURL function such as POSTFIELDS and RETURNTRANSFER. You have many other options that you can add to CURL PHP. Have a look in the PHP docs to find out the best approach for your code logic.

##### Conclusion:

REST API request is a quite simple way to get, insert, and update data through internet with small effort. Nowadays, Mostly of services through the internet has implemented REST API functions and RACKCORP also has its own standard. If you need to connect to us using REST API, read more in <span style="color: #3598db;">[RACKCORP REST API](https://wiki.rackcorp.com/books/help-and-support-en/page/rackcorp-rest-api)</span>