Objective 6.5

Describe characteristics of REST-based APIs (authentication types, CRUD, HTTP verbs, and data encoding)

What an API is

An API (application programming interface) is a contract that says “if you send me a request in this format, I will do this and reply in that format.” APIs let one program use the features of another without needing to understand its internals. Modern network controllers, cloud platforms, and even individual IOS-XE devices expose APIs so that scripts can manage them.

What makes an API “RESTful”

REST (Representational State Transfer) is not a protocol; it is an architectural style described by Roy Fielding in 2000. An API that follows REST’s rules is called RESTful. REST APIs almost always run over HTTP or HTTPS, use URIs to name the things being managed (called resources), use the standard HTTP methods to say what to do, and carry data in a format like JSON or XML. The six REST constraints appear on the exam as “characteristics of REST APIs.”

REST constraint Meaning
Client-server The client (script, app) and the server (controller, device) are separate; each can evolve independently
Stateless Every request contains all the information the server needs; the server does not remember previous requests. Any authentication token must be sent with each request
Cacheable Responses indicate whether they may be cached by the client to reduce repeated requests
Uniform interface Resources are identified by URIs, manipulated with the standard HTTP methods, and represented in a standard format (JSON/XML)
Layered system The client cannot tell whether it is talking directly to the server or through intermediaries (load balancers, proxies, gateways)
Code on demand (optional) The server may send executable code (such as JavaScript) to the client; this is the only optional constraint

Anatomy of a URI

A REST resource is identified by a URI (Uniform Resource Identifier). The exam expects you to name the parts.

https://catalyst.example.com:443/dna/intent/api/v1/network-device?hostname=SW1
\___/   \______________________/\_______________________________/ \__________/
scheme          authority                    path                    query
(protocol)  (host and optional port)     (which resource)        (parameters)
  • Scheme: the protocol, http or https.
  • Authority: the hostname or IP address, optionally with a port (:443). Sometimes user credentials appear here too, but that is discouraged.
  • Path: identifies the resource, for example /dna/intent/api/v1/network-device. Paths often include an API version (v1).
  • Query: optional parameters after a ?, joined with &, used to filter or page results (?hostname=SW1&limit=10).
  • The parts before the path (scheme://authority) are sometimes called the URL base, and the path plus query is called the resource or endpoint. (Technically a URL is a type of URI that includes the location; on the exam the terms are used interchangeably.)

CRUD and the HTTP verbs

Nearly every management task can be expressed as one of four operations, abbreviated CRUD: Create, Read, Update, Delete. REST maps each of these to an HTTP method (verb).

CRUD operation HTTP verb Meaning Idempotent?
Create POST Create a new resource; the server usually assigns the ID No (repeating creates duplicates)
Read GET Retrieve a resource or a list; makes no changes Yes
Update PUT Replace the whole resource with the body supplied Yes
Update PATCH Modify only the fields supplied Depends
Delete DELETE Remove the resource Yes

Idempotent means doing the operation several times has the same result as doing it once. Reading a VLAN list ten times does not change anything; deleting VLAN 30 five times leaves you with the same result as deleting it once (it is gone). Creating a VLAN five times with POST could create five objects, so POST is not idempotent. This word also appears in the Ansible and Terraform section.

HTTP headers

An HTTP request and response both carry headers, which are key/value lines that describe the message. The ones that matter for REST APIs:

Header Direction Purpose
Content-Type Request or response The format of the body being sent, e.g. application/json or application/xml
Accept Request The format the client wants back, e.g. application/json
Authorization Request Carries credentials: Basic <base64>, Bearer <token>, or a vendor-specific token
X-Auth-Token Request Cisco Catalyst Center’s header for its session token (an API-key-style header)
Cache-Control Response Whether and how long the response may be cached

HTTP status codes

The server’s response starts with a three-digit status code. The first digit tells you the class; the exact codes below are the ones to memorize.

Class Meaning Codes to know
1xx Informational Rarely seen in APIs
2xx Success 200 OK (request succeeded; typical for GET), 201 Created (POST created a resource), 204 No Content (success but no body; typical for DELETE)
3xx Redirection 301 Moved Permanently, 302 Found (temporary redirect), 304 Not Modified (cached copy still valid)
4xx Client error (you did something wrong) 400 Bad Request (malformed syntax or JSON), 401 Unauthorized (not authenticated or bad credentials), 403 Forbidden (authenticated but not allowed), 404 Not Found (bad URI/resource does not exist), 405 Method Not Allowed, 429 Too Many Requests (rate limited)
5xx Server error (the server failed) 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

Authentication types

Because REST is stateless, every request must prove who the client is. The common methods:

Method How it works Notes
Basic authentication Username and password joined with a colon, Base64-encoded, sent in Authorization: Basic ... Base64 is encoding, not encryption; must be used over HTTPS. Simple but weakest
Bearer token / token-based The client first authenticates (often with basic auth) and receives a token; the token is then sent with every request, typically Authorization: Bearer <token> Tokens expire; Catalyst Center issues a token via POST to /dna/system/api/v1/auth/token and expects it back in the X-Auth-Token header
API key A long secret string issued by the server administrator, sent in a header or query parameter Common on cloud services (Meraki uses X-Cisco-Meraki-API-Key); the key identifies the application and should be rotated
OAuth 2.0 An authorization framework; the user logs in with an identity provider and the application receives a scoped access token without ever seeing the user’s password Used by cloud services (Webex, Google, Microsoft); supports delegated, limited-scope access; tokens are usually bearer tokens
Certificate-based (mutual TLS) The client presents a digital certificate during the TLS handshake Strong; used in machine-to-machine environments

Data encoding: JSON, XML, and YAML

The body of a REST request or response has to be in a format both sides understand. Three text formats dominate.

Format Full name Typical use Characteristics
JSON JavaScript Object Notation REST API bodies (the default almost everywhere) Braces and brackets; lightweight; maps directly to data structures in Python and JavaScript
XML eXtensible Markup Language NETCONF, older SOAP APIs, some RESTCONF Tags like <name>SW1</name>; verbose; supports schemas and namespaces
YAML YAML Ain’t Markup Language Ansible playbooks, configuration files, Kubernetes Indentation-based; no braces; most human-readable; a superset of JSON

The same data in all three formats:

JSON:
{
  "hostname": "SW1",
  "vlans": [10, 20],
  "managed": true
}

XML:
<device>
  <hostname>SW1</hostname>
  <vlans>
    <vlan>10</vlan>
    <vlan>20</vlan>
  </vlans>
  <managed>true</managed>
</device>

YAML:
hostname: SW1
vlans:
  - 10
  - 20
managed: true

Notice that YAML uses indentation (spaces, never tabs) to show structure, a dash for each list item, and does not require quotes around simple strings. XML wraps every value in an opening and closing tag. JSON uses braces for objects and square brackets for lists (section 6.7 covers JSON in depth).

A complete REST example

Here is what a request to Cisco Catalyst Center’s northbound API looks like. First the client gets a token, then it asks for the device list.

POST /dna/system/api/v1/auth/token HTTP/1.1
Host: catalyst.example.com
Authorization: Basic YWRtaW46Q2lzY28xMjM=
Content-Type: application/json

--- response ---
HTTP/1.1 200 OK
Content-Type: application/json

{ "Token": "eyJ0eXAiOiJKV1QiLCJhbGciOi...(truncated)" }

--- second request ---
GET /dna/intent/api/v1/network-device HTTP/1.1
Host: catalyst.example.com
X-Auth-Token: eyJ0eXAiOiJKV1QiLCJhbGciOi...(truncated)
Accept: application/json

--- response ---
HTTP/1.1 200 OK
Content-Type: application/json

{
  "response": [
    {
      "hostname": "CORE-SW1",
      "managementIpAddress": "10.1.1.1",
      "platformId": "C9300-48P",
      "reachabilityStatus": "Reachable"
    }
  ],
  "version": "1.0"
}

The same request in Python using the popular requests library (you will not be asked to write this, but seeing it helps the concepts stick):

import requests

url = "https://catalyst.example.com/dna/intent/api/v1/network-device"
headers = {"X-Auth-Token": token, "Accept": "application/json"}
resp = requests.get(url, headers=headers, verify=False)
print(resp.status_code)          # 200
for dev in resp.json()["response"]:
    print(dev["hostname"], dev["managementIpAddress"])