Skip to content

Expert · Automation, SDN and cloud networking · topic 51 of 57 · 35 min

REST APIs and JSON

Explanation

A REST API lets a program read and change things on a controller or device by sending HTTP requests to URLs. The HTTP method says what to do (GET reads, POST creates, PUT or PATCH updates, DELETE removes), and the status code in the reply says how it went. The data travels as JSON: objects in curly braces, arrays in square brackets, and text always in double quotes.

What a REST API is

REST (representational state transfer) is a style of API that uses ordinary HTTP, the same protocol your browser uses for web pages. Everything the API manages, such as a device, an interface or a VLAN, is a resource with its own address called a URI (uniform resource identifier), for example https://catalyst.example.com/dna/intent/api/v1/network-device. A program sends a request to that URI and gets a response, usually in JSON.

REST APIs are stateless: the server does not remember earlier requests. Every request must carry everything needed, including who you are (usually a token in a header). This makes the server simpler and easier to scale.

HTTP methods and CRUD

CRUD stands for create, read, update and delete: the four things you can do with data. Each maps to an HTTP method.

CRUD actionHTTP methodNetwork example
CreatePOSTAdd a new VLAN or a new device to the controller
ReadGETList all devices, or show one interface
UpdatePUT (replace the whole thing) or PATCH (change some fields)Change the description of an interface
DeleteDELETERemove a VLAN

Status codes: how did it go?

CodeMeaningTypical cause
200 OKSuccess, and here is the dataA GET that worked
201 CreatedA new resource was madeA POST that added a VLAN
204 No ContentSuccess, nothing to send backA DELETE or an update that worked
400 Bad RequestThe server could not understand the requestBroken JSON or a missing field
401 UnauthorizedYou are not logged in (no valid token)Token missing or expired
403 ForbiddenYou are logged in but not allowed to do thisA read-only user tried to delete
404 Not FoundNo resource at that URIA typo in the URL or a wrong device ID
500 Internal Server ErrorSomething broke on the server sideA bug or failure in the controller
Tip: Remember the families: 2xx means success, 4xx means you (the client) did something wrong, 5xx means the server failed.

Headers

Headers are extra lines of information sent with a request or response. Content-Type tells the other side what format the body is in, for example application/json. Accept says which format you want back. Authorization (or a product-specific header such as X-Auth-Token on Catalyst Center) carries your credentials or token. A token is a long random string the server gives you after you log in once; you send it with every later request instead of your password.

bash
# 1. Log in once and get a token (curl asks for the password)
curl -s -X POST -u admin https://catalyst.example.com/dna/system/api/v1/auth/token

# 2. Send the token with every later request
curl -s -H "X-Auth-Token: $TOKEN" -H "Accept: application/json" https://catalyst.example.com/dna/intent/api/v1/network-device
curl is a command-line HTTP client. -X sets the method, -u gives a username, -H adds a header. The host name is an example.

JSON syntax

JSON (JavaScript Object Notation) is a text format for data that both people and programs can read. It has a few simple building blocks:

  • Object: key and value pairs inside curly braces, like {"hostname": "SW1"}. Keys are always strings.
  • Array: an ordered list inside square brackets, like [10, 20, 30].
  • String: text in double quotes. Single quotes are not allowed.
  • Number: 1500 or 2.5, with no quotes.
  • true, false and null: written in lower case, with no quotes.
json
{
  "hostname": "SW-PUNE-01",
  "managementIp": "10.20.1.2",
  "reachable": true,
  "uptimeDays": 41,
  "location": null,
  "vlans": [10, 20, 99],
  "interfaces": [
    {"name": "GigabitEthernet1/0/1", "status": "up", "vlan": 10},
    {"name": "GigabitEthernet1/0/2", "status": "down", "vlan": 20}
  ]
}
A simplified device response. vlans is an array of numbers; interfaces is an array of objects.

To read this in Python, json.loads(text) turns the JSON text into dicts and lists. data["interfaces"][1]["status"] then gives "down". json.dumps(data) does the opposite and turns Python data back into JSON text.

Careful: Common JSON mistakes: single quotes around strings, a trailing comma after the last item ({"a": 1,}), comments (JSON has none), True or None written the Python way instead of true or null, and missing quotes around keys. Any one of these makes the whole document invalid, and the API answers 400 Bad Request. Paste the JSON into a validator, or try json.loads in Python, to find the exact line.

JSON, XML and YAML

FormatLooks likeWhere you meet it
JSON{"vlan": 10, "name": "SALES"}REST APIs, RESTCONF, most controllers
XML<vlan><id>10</id><name>SALES</name></vlan>NETCONF, older APIs
YAMLvlan: 10 and name: SALES on separate lines, using indentationAnsible playbooks, Kubernetes, many config files

All three describe the same kind of structured data. JSON is compact and strict. XML uses opening and closing tags and is more wordy. YAML is the easiest for people to write, but its indentation must be exactly right, and it allows comments starting with #.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

REST APIs and JSON · 1/8

REST APIs and JSON

In this lesson you will learn how programs talk to network controllers and devices: REST APIs and JSON.

Prefer a video by a teacher? Find free videos on “REST API JSON for network engineers CCNA HTTP methods status codes” on YouTube ↗

In real life: Finding down ports before the morning rush

A NOC (network operations centre) engineer at a bank in Mumbai runs a small Python script at 8 am. It calls the controller's REST API with a token, gets the interface list for 50 branch switches as JSON, and prints any interface that is down. Instead of logging in to 50 switches, she sees in one minute that the ATM port at the Andheri branch is down and raises a ticket before the branch opens.

python
import json

reply = '{"interfaces": [{"name": "Gi1/0/1", "status": "up"}, {"name": "Gi1/0/7", "status": "down"}]}'
data = json.loads(reply)
for intf in data["interfaces"]:
    if intf["status"] == "down":
        print("DOWN:", intf["name"])
Shows DOWN: Gi1/0/7. In real life reply comes from the API instead of a fixed string.

Practice (0/4 done)

Task 1 · Code · Python

A controller returns the VLANs of a switch as JSON text like {"vlans": [{"id": 10, "name": "SALES"}, {"id": 20, "name": "HR"}]}. Write count_vlans(payload) that takes this JSON text and returns how many VLANs it contains.

Task 2 · Code · Python

Write down_interfaces(payload). payload is JSON text like {"interfaces": [{"name": "Gi1/0/1", "enabled": true, "status": "up"}, ...]}. Return a list of the names of the interfaces whose status is "down", in the order they appear.

Task 3 · Code · Python

Before sending a body to an API, a careful script checks it. Write is_valid_json(text) that returns True if text is valid JSON and False if it is not. Use json.loads inside try and except (json.loads raises ValueError, and its subclass json.JSONDecodeError, on bad JSON).

Task 4 · Question

Which line makes this JSON invalid? 1: { 2: "hostname": "R1", 3: "ports": [1, 2, 3], 4: 'site': "Pune" 5: }

Quick quiz

Question 1

1.Which HTTP method reads data without changing it?

Question 2

2.Your script gets 401 Unauthorized. What is the most likely cause?

Question 3

3.Which value is valid JSON?

Question 4

4.What does "stateless" mean for a REST API?

Question 5

5.Which data format do Ansible playbooks use?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which HTTP method reads data without changing it?

Answer: GET

GET is the read in CRUD. POST creates, PUT updates and DELETE removes.

Your script gets 401 Unauthorized. What is the most likely cause?

Answer: The token is missing or has expired

401 means the server does not know who you are. Log in again to get a fresh token. A typo in the URL usually gives 404.

Which value is valid JSON?

Answer: {"up": true}

JSON needs double quotes, lower-case true and no trailing comma.

What does "stateless" mean for a REST API?

Answer: Each request carries everything needed, such as the token; the server does not remember earlier requests

Stateless means no memory of earlier requests, so every request includes its own authentication and data.

Which data format do Ansible playbooks use?

Answer: YAML

Ansible playbooks are written in YAML, which uses indentation instead of braces.

Which HTTP method should delete a resource?Related

Answer: DELETE

DELETE removes the resource at the URL.

From REST API design and JSON handlers

A POST /products request adds a new product. What should the response contain?Related

Answer: Status 201 and the new product with its id

201 Created, with the new record, so the app knows the new id.

From Handling requests: a full CRUD API

Which URL follows REST naming best?Related

Answer: /products

REST URLs are plural nouns. The method (GET) already says what to do.

From What an API is and how REST APIs are designed

Which part of an HTTP request carries the JSON data you send?Related

Answer: The body

The body comes after the headers and the empty line, and holds the data.

From HTTP requests, responses and methods

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Automation, SDN and cloud networking” before its exam: Configuration management: Ansible, Puppet, Chef and NETCONF, Virtualisation, VRFs and cloud networking.
  2. Module 11 exam: Automation, SDN and cloud networking · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Troubleshooting and the CCNA exam. 57 topics left in the course before the final exam.

← Previous: Why automate: SDN and controller-based networking