Lesson Overview
Modern network automation depends on APIs, structured data, and automation tools that allow software to read network state and make repeatable configuration changes. REST APIs commonly use HTTP or HTTPS to exchange requests and responses, while CRUD describes the basic operations used to create, read, update, and delete resources.
This lesson explains how REST, HTTP methods, status codes, and JSON work together in network programmability. It also introduces Ansible and Terraform as automation and Infrastructure-as-Code tools: Ansible commonly executes task-based configuration and operational workflows, while Terraform uses a declarative model to build and maintain desired infrastructure state. The focus is on understanding how these technologies fit into controller-based and API-driven network operations.
Learning objectives
- By the end of this lesson, a learner should be able to:
- Explain REST and identify a resource, URI/endpoint, request, response, header, and body.
- Map CRUD operations to common HTTP methods and interpret common HTTP status codes.
- Recognize common API authentication methods and explain why HTTPS is important.
- Read JSON objects, arrays, keys, values, nested structures, and basic data types.
- Describe Ansible components such as inventory, playbooks, modules/collections, variables, and templates.
- Describe Terraform components such as HCL configuration, providers, resources, state, plan, and apply.
- Compare Ansible and Terraform at a CCNA level and identify common use cases for each.
- Follow a safe automation workflow: baseline → change → verify → rollback if required.
|
Key idea: APIs provide a programmable interface, JSON commonly carries the data, and tools such as Ansible and Terraform automate repeatable changes using those interfaces. |
1. REST fundamentals
1.1 What is REST?
REST (Representational State Transfer) is an architectural style commonly used to build web APIs. In networking, a REST API allows an application, script, automation tool, or controller to read information from a platform and request changes without manually logging in to every device.
A REST API exposes resources. A resource can represent a device, interface, VLAN, site, policy, user, route, wireless network, or many other manageable objects. The client identifies the resource by a URI and uses an HTTP method to state the desired action.
Client: the script, application, automation platform, or API tool sending the request.
Server/API endpoint: the controller or device that exposes the REST interface.
Resource: the object being read or changed, such as a device or interface.
URI/URL: the path that identifies where the resource is exposed.
Method: GET, POST, PUT, PATCH, DELETE, and other HTTP methods.
Headers: metadata such as authentication, accepted format, and content type.
Body: optional data sent with the request or returned in the response, commonly JSON.
Status code: a numeric result such as 200, 201, 401, 404, or 500.
1.2 REST is normally stateless
Stateless means the server does not need to remember a previous request in order to understand the next request. Each request normally carries the information needed to process it, such as the resource URI, method, authentication context, and required data. Authentication systems can still use tokens or sessions; the key REST idea is that the request itself is self-contained enough for the server to act on it.
1.3 REST resource examples
|
Resource idea |
Example URI |
Possible operation |
|
Device inventory |
/api/v1/devices |
GET all devices |
|
Single device |
/api/v1/devices/R1 |
GET / PATCH device |
|
Interfaces |
/api/v1/devices/R1/interfaces |
GET interfaces |
|
VLANs |
/api/v1/vlans |
GET / POST VLANs |
|
Policy |
/api/v1/policies/branch-access |
GET / PATCH policy |
2. CRUD and HTTP methods
2.1 CRUD
CRUD is a simple way to describe the four basic operations performed on data: Create, Read, Update, and Delete. Network APIs often expose these operations using standard HTTP methods.
|
CRUD |
Common HTTP method |
Typical meaning |
|
Create |
POST |
Create a new resource in a collection. |
|
Read |
GET |
Retrieve a resource or collection. |
|
Update |
PUT |
Replace the representation of a resource. |
|
Update |
PATCH |
Modify only selected fields of a resource. |
|
Delete |
DELETE |
Remove a resource. |
|
Exam note: The CRUD-to-HTTP mapping is a common convention, but the actual API documentation defines exactly which methods are supported for each endpoint. |
2.2 GET - Read
GET asks the API to return data. It should not be used to intentionally change the resource. Examples include retrieving inventory, interface status, routing information, or a configuration object.
Example GET request
|
GET /api/v1/devices/R1 HTTP/1.1 Host: controller.example Authorization: Bearer <token> Accept: application/json |
2.3 POST - Create or submit
POST commonly creates a new resource under a collection URI or submits an action to a server. A successful creation frequently returns HTTP 201 Created and may include a Location header identifying the new resource.
Example POST request
|
POST /api/v1/vlans HTTP/1.1 Authorization: Bearer <token> Content-Type: application/json
{ "id": 10, "name": "USERS" } |
2.4 PUT vs PATCH
PUT is commonly used to replace the full representation of a resource. PATCH is commonly used to modify only selected fields. Because API behavior varies, always read the endpoint documentation before assuming whether PUT, PATCH, or both are supported.
2.5 DELETE
DELETE requests removal of the identified resource. A successful deletion often returns 204 No Content or another 2xx status depending on the API.
3. HTTP and HTTPS for APIs
3.1 Request structure
An HTTP request contains a request line, headers, and sometimes a body. REST APIs normally use HTTPS rather than clear-text HTTP so credentials, tokens, and configuration data are protected in transit.
3.2 Important headers
|
Header |
Purpose |
Example |
|
Authorization |
Carries authentication information. |
Bearer <token> |
|
Content-Type |
Describes the request body format. |
application/json |
|
Accept |
States the response format the client wants. |
application/json |
|
Host |
Identifies the API host. |
controller.example |
|
If-Match / ETag |
Can support safe conditional updates. |
API dependent |
3.3 Common HTTP status codes
|
Code |
Meaning |
Interpretation |
|
200 OK |
Request succeeded |
Common for successful GET or update. |
|
201 Created |
Resource created |
Common successful POST creation. |
|
204 No Content |
Succeeded without response body |
Common for successful update/delete. |
|
400 Bad Request |
Malformed or invalid request |
Check syntax, JSON, fields, or parameters. |
|
401 Unauthorized |
Authentication required/failed |
Check credentials or token. |
|
403 Forbidden |
Authenticated but not permitted |
Check role/authorization. |
|
404 Not Found |
URI/resource not found |
Check endpoint and resource ID. |
|
405 Method Not Allowed |
Method unsupported on URI |
Check API documentation. |
|
409 Conflict |
Request conflicts with current state |
Resource/state conflict. |
|
500 Server Error |
Server-side failure |
Request reached server but processing failed. |
3.4 Authentication types
The CCNA v1.1 blueprint explicitly calls out authentication types for REST APIs. At CCNA level, understand the purpose rather than memorizing vendor-specific token flows.
|
Type |
How it works |
Important point |
|
Basic authentication |
Username and password are carried in the HTTP Authorization header. |
Use only with HTTPS; Base64 is encoding, not encryption. |
|
Token / Bearer |
Client sends a previously obtained token. |
Common for controller and cloud APIs. |
|
API key |
Client sends a generated key in a header or parameter. |
Treat keys like secrets. |
|
OAuth |
Delegated token-based authorization framework. |
Common with modern application APIs; exact flow varies. |
4. JSON data encoding
4.1 What is JSON?
JSON (JavaScript Object Notation) is a lightweight text format used to represent structured data. Network controllers and REST APIs commonly send and receive JSON because it is easy for both humans and programs to parse.
4.2 JSON syntax rules
Objects use curly braces: { }.
Arrays use square brackets: [ ].
A key is followed by a colon and its value: "hostname": "R1".
Key names and string values use double quotation marks.
Numbers are not quoted.
Boolean values are true or false in lowercase.
null represents an intentionally empty/no value.
Commas separate members, but standard JSON does not allow a trailing comma after the final member.
Standard JSON does not support comments.
4.3 Objects vs arrays
An object groups named properties. An array is an ordered list of values or objects. A common network API response is an object containing an array of interface objects.
Nested JSON example
|
{ "device": "R1", "interfaces": [ {"name": "GigabitEthernet1", "status": "up"}, {"name": "GigabitEthernet2", "status": "down"} ] } |
4.4 Reading JSON step by step
Start with the outermost object or array.
Identify the key you need, for example interfaces.
If the value is an array, examine each array element.
If an element is an object, read its child keys such as name and status.
Pay attention to data types. "1500" is a string, while 1500 is a number.
4.5 JSON vs XML at a glance
|
JSON |
XML |
|
Uses objects, arrays, keys, values. |
Uses elements, attributes, and tags. |
|
Usually more compact for API payloads. |
Can be more verbose. |
|
Common with REST APIs. |
Common with NETCONF and many structured-data systems. |
|
Data types can be obvious in JSON literals. |
Schema/model can define types externally. |
5. End-to-end REST API workflow
5.1 Read before change
A safe automation workflow normally begins by reading current state. The script can confirm the correct device, interface, or object before sending a change. This reduces the chance of applying a valid request to the wrong target.
Authenticate to the controller or device.
GET the current resource and record the baseline.
Validate the returned status code and JSON data.
Prepare the desired change.
Send POST, PUT, or PATCH as required.
Check the HTTP result and response body.
GET the resource again to verify actual state.
If validation fails, stop or execute the approved rollback procedure.
5.2 Example API sequence
Illustrative REST workflow
|
# 1) Read device state curl -s -H "Authorization: Bearer $TOKEN" -H "Accept: application/json" https://controller.example/api/v1/devices/R1
# 2) Submit a change (example endpoint/payload) curl -X PATCH -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"description":"MANAGED_BY_API"}' https://controller.example/api/v1/devices/R1/interfaces/Gi1
# 3) Re-read the resource and validate curl -s -H "Authorization: Bearer $TOKEN" https://controller.example/api/v1/devices/R1/interfaces/Gi1 |
|
Important: Endpoint paths, authentication, payloads, and media types vary by product. Treat examples as learning patterns and use the real platform API documentation in production. |
6. API troubleshooting
|
Symptom |
Likely cause |
What to check |
|
401 |
Authentication failed/expired |
Username, password, token, token expiration, auth scheme. |
|
403 |
Authenticated but unauthorized |
RBAC role, API permissions, policy. |
|
404 |
Wrong endpoint/resource |
Base URL, version, resource ID, path spelling. |
|
400 |
Invalid request |
JSON syntax, required fields, parameter types. |
|
405 |
Wrong HTTP method |
Endpoint supports different verb. |
|
409 |
State/resource conflict |
Existing object, dependency, optimistic locking. |
|
TLS error |
Certificate/HTTPS issue |
Certificate trust, hostname, date/time, TLS settings. |
|
Unexpected JSON |
Schema/version changed |
API version, field name, pagination, response wrapper. |
7. Ansible fundamentals
7.1 What is Ansible?
Ansible is an automation and configuration-management tool. A control node reads inventory and playbooks, then uses modules or collections to communicate with target systems. For network automation, Ansible commonly uses SSH, network CLI transports, NETCONF, RESTCONF, or vendor APIs without requiring an Ansible agent to be installed on the network device.
7.2 Core Ansible components
|
Component |
Purpose |
|
Control node |
System from which Ansible runs. |
|
Inventory |
Lists managed hosts, groups, addresses, and variables. |
|
Playbook |
YAML file describing plays and tasks. |
|
Task |
One action executed by a module. |
|
Module / collection |
Reusable code for a platform or action. |
|
Variable |
Reusable data such as VLAN ID, hostname, interface, site, or credentials reference. |
|
Template |
Generates structured configuration from variables, commonly with Jinja2. |
|
Handler |
Action triggered by a change, often used to restart/reload a service. |
|
Facts / gathered data |
Information collected from the managed target. |
|
Idempotency |
Running the same desired task repeatedly should not keep making unnecessary changes. |
7.3 Inventory example
inventory.ini
|
[routers] R1 ansible_host=192.0.2.11 R2 ansible_host=192.0.2.12
[routers:vars] ansible_connection=ansible.netcommon.network_cli ansible_network_os=cisco.ios.ios ansible_user=labadmin |
|
Security practice: Do not place production passwords or API secrets in plain text files. Use an approved secret store, Ansible Vault, environment injection, or another protected mechanism. |
7.4 Playbook example
playbook.yml
|
--- - name: Configure and verify a router description hosts: routers gather_facts: no
tasks: - name: Pre-check cisco.ios.ios_command: commands: - show ip interface brief register: before
- name: Configure Loopback0 description cisco.ios.ios_config: parents: interface Loopback0 lines: - description MANAGED_BY_ANSIBLE
- name: Verify cisco.ios.ios_command: commands: - show running-config interface Loopback0 register: after |
7.5 Why idempotency matters
If the desired configuration is already present, an idempotent module should report no change rather than pushing the same command again. This makes automation safer, easier to audit, and more predictable.
8. Terraform fundamentals
8.1 What is Terraform?
Terraform is an Infrastructure as Code tool that uses declarative configuration. Instead of describing every manual step, the configuration describes the desired infrastructure resources. Terraform uses provider plugins to talk to external platforms and a state model to understand resources it manages.
8.2 Core Terraform components
|
Component |
Purpose |
|
HCL configuration |
Human-readable configuration describing desired infrastructure. |
|
Provider |
Plugin that communicates with a platform API. |
|
Resource |
An object Terraform manages. |
|
Data source |
Reads information without managing the object. |
|
Variable |
Input value that makes configuration reusable. |
|
Output |
Value displayed/exported after evaluation. |
|
State |
Terraform record of managed resources and attributes. |
|
Plan |
Preview of proposed create/change/destroy operations. |
|
Apply |
Executes the approved plan. |
|
Module |
Reusable group of Terraform configuration. |
8.3 Terraform command flow
Common Terraform workflow commands
|
terraform init terraform fmt terraform validate terraform plan terraform apply terraform show terraform destroy # only when removal is intended and approved |
8.4 HCL structure - conceptual networking example
The exact provider and resource names vary by platform. The following example is intentionally provider-neutral and illustrates HCL structure rather than a directly executable configuration.
Conceptual HCL example
|
terraform { required_providers { network = { source = "vendor/network" } } }
provider "network" { endpoint = var.controller_url }
resource "network_vlan" "users" { vlan_id = 10 name = "USERS" }
output "users_vlan_id" { value = network_vlan.users.vlan_id } |
8.5 Terraform state
State is one of the most important Terraform concepts. It allows Terraform to map configuration to managed objects and calculate what must change. State may contain identifiers and sensitive values, so it must be protected. Team environments commonly use a secured remote backend with locking and access control.
8.6 Drift
Drift occurs when the real infrastructure changes outside the expected Terraform workflow. The next plan may detect differences between desired configuration, recorded state, and the provider-reported current environment. The engineer must understand the proposed change before applying it.
9. Ansible vs Terraform
Ansible and Terraform are both automation tools, but they solve different problems. Ansible is primarily used for configuration management, orchestration, validation, and operational automation, while Terraform is primarily used for declarative infrastructure provisioning and resource lifecycle management.
Ansible
Ansible follows a task- and playbook-oriented workflow. An administrator defines devices in an inventory and writes YAML playbooks containing tasks that should be executed.
Terraform
Terraform follows a declarative desired-state model. Instead of defining a sequence of operational tasks, you describe what infrastructure should exist.
|
Topic |
Ansible |
Terraform |
|
Primary model |
Task/playbook automation |
Declarative desired-state infrastructure |
|
Common network use |
Configure, validate, collect, orchestrate |
Provision/manage lifecycle where a provider exposes resources |
|
Inventory |
Explicit inventory/groups |
Resources discovered/managed through config + state + provider |
|
State file |
No Terraform-style central state required |
State is a core concept |
|
Change preview |
Check mode/diff depending on module |
terraform plan is central |
|
Language |
YAML playbooks |
HCL configuration |
|
Transport |
SSH, CLI, NETCONF, RESTCONF, APIs |
Provider APIs |
|
Overlap |
Can provision and configure |
Can sometimes configure network resources too |
|
Remember: These tools overlap. At CCNA level, focus on their core operating models and common strengths rather than treating either one as limited to a single task type. |
10. Safe automation design
10.1 Source of truth and inputs
Automation scales both correct and incorrect data. Before a workflow changes many devices, verify inventory, IP addressing, site identifiers, variables, templates, and intended scope. A bad source of truth can create a large blast radius.
10.2 Pre-check, change, post-check
Pre-check: capture current configuration/state and confirm prerequisites.
Change: apply the smallest approved change to the intended targets.
Post-check: confirm the result and test connectivity or service health.
Audit: save API/task results, changed objects, timestamps, and approvals.
Rollback: use an approved rollback method when validation fails.
10.3 Idempotency and repeatability
Repeatable automation should produce the same intended state without introducing new changes every time it runs. Idempotent operations are especially useful for configuration baselines and compliance enforcement.
|
Website teaching sequence: Teach REST → HTTP/CRUD → JSON first, then introduce Ansible and Terraform. Learners understand the tools much faster when they already understand the APIs and data formats underneath them. |
Quick knowledge check
1. What does HTTP 401 normally indicate?
Answer: Authentication is required or failed.
2. What does HTTP 403 normally indicate?
Answer: The client is authenticated but not authorized for the requested operation.
3. What does idempotent mean?
Answer: Repeated execution reaches the same desired state without unnecessary repeated changes.
4. Which tool is especially associated with playbooks and agentless network configuration?
Answer: Ansible.
