Expert · Automation, SDN and cloud networking · topic 51 of 57 · 35 min
REST APIs and JSON
Explanation
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 action | HTTP method | Network example |
|---|---|---|
| Create | POST | Add a new VLAN or a new device to the controller |
| Read | GET | List all devices, or show one interface |
| Update | PUT (replace the whole thing) or PATCH (change some fields) | Change the description of an interface |
| Delete | DELETE | Remove a VLAN |
Status codes: how did it go?
| Code | Meaning | Typical cause |
|---|---|---|
| 200 OK | Success, and here is the data | A GET that worked |
| 201 Created | A new resource was made | A POST that added a VLAN |
| 204 No Content | Success, nothing to send back | A DELETE or an update that worked |
| 400 Bad Request | The server could not understand the request | Broken JSON or a missing field |
| 401 Unauthorized | You are not logged in (no valid token) | Token missing or expired |
| 403 Forbidden | You are logged in but not allowed to do this | A read-only user tried to delete |
| 404 Not Found | No resource at that URI | A typo in the URL or a wrong device ID |
| 500 Internal Server Error | Something broke on the server side | A bug or failure in the controller |
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.
# 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-deviceJSON 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.
{
"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}
]
}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.
JSON, XML and YAML
| Format | Looks like | Where 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 |
| YAML | vlan: 10 and name: SALES on separate lines, using indentation | Ansible 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
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.
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"])Practice (0/4 done)
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.
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.
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).
Which line makes this JSON invalid? 1: { 2: "hostname": "R1", 3: "ports": [1, 2, 3], 4: 'site': "Pune" 5: }
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Configuration management: Ansible, Puppet, Chef and NETCONFAutomation, SDN and cloud networking · same module
- Virtualisation, VRFs and cloud networkingAutomation, SDN and cloud networking · same module
- REST API design and JSON handlersGo Programming (backend and cloud) · Building a REST API with a database
- Handling requests: a full CRUD APIBackend Development · APIs and request handling
- What an API is and how REST APIs are designedBackend Development · APIs and request handling
- HTTP requests, responses and methodsBackend Development · How the web and backends work
Questions people ask about this
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
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.
Which URL follows REST naming best?Related
Answer: /products
REST URLs are plural nouns. The method (GET) already says what to do.
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.
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
- 2 more topics in “Automation, SDN and cloud networking” before its exam: Configuration management: Ansible, Puppet, Chef and NETCONF, Virtualisation, VRFs and cloud networking.
- Module 11 exam: Automation, SDN and cloud networking · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- 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