REST APIs and Authentication (CCNA 200-301 Topic 6.5)
API and REST Fundamentals
- Concept: An API (Application Programming Interface) is a software interface that allows two applications to communicate and exchange data.
- REST (Representational State Transfer) is not a specific protocol, but a framework/architecture of rules and constraints for building APIs.
- SDN Context: REST APIs are primarily used for the Northbound Interface (NBI) between applications and the SDN controller. (Southbound interfaces typically use NETCONF/RESTCONF).
- Protocol: While REST APIs can use various protocols, HTTP/HTTPS is the most common application-layer protocol used for communication.
CRUD Operations and HTTP Verbs
REST APIs map standard database operations (CRUD) to specific HTTP methods (verbs).
| CRUD Operation | HTTP Verb | Description |
|---|---|---|
| Create | POST |
Creates a new variable/resource and sets its initial value. |
| Read | GET |
Retrieves the value or data of an existing resource. |
| Update | PUT / PATCH |
Changes the value of an existing resource. (PUT replaces, PATCH modifies). |
| Delete | DELETE |
Removes a variable/resource from the server. |
Things to note: PUT can sometimes be categorized as a Create action if it creates a new resource, but it is primarily used for Updates.
HTTP Request and Response Structure
URI Components
A Uniform Resource Identifier (URI) identifies the resource. A URL is a specific type of URI.
- Scheme: The protocol used (e.g.,
httporhttps). - Authority: The address or hostname of the server (e.g.,
api.cisco.com). - Path: The specific resource being accessed (e.g.,
/dna/intent/api/v1/network-device).
HTTP Request Format
POST /api/v1/acl/rules HTTP/2
Host: api.example.com
Accept: application/json
Authorization: Basic <base64_encoded_credentials>
{ "data": "payload" }
- Start Line: HTTP Method, URI/URL, HTTP Version.
- Headers: Metadata about the request (e.g.,
Accepttells the server what data format the client can handle, like JSON or XML). - Blank Line: Separates headers from the body.
- Message Body: The actual data/payload being sent (common in
POST/PUT).
HTTP Response Status Codes
The first digit indicates the class of the response:
- 1xx (Informational): Request received, continuing process.
- Example:
102 Processing(Server received request but response is not yet available).
- Example:
- 2xx (Successful): Request successfully received, understood, and accepted.
- Example:
200 OK(Request succeeded, resource returned in body). - Example:
201 Created(Request succeeded and a new resource was created, e.g., after aPOST).
- Example:
- 3xx (Redirection): Further action required to complete the request.
- Example:
301 Moved Permanently(Resource has a new URI).
- Example:
- 4xx (Client Error): Error in the request; it cannot be fulfilled.
- Example:
403 Forbidden(Client must authenticate/authorize; often colloquially called “Unauthorized”). - Example:
404 Not Found(Requested resource does not exist on the server).
- Example:
- 5xx (Server Error): Valid request, but server failed to fulfill it.
- Example:
500 Internal Server Error(Unexpected server condition).
- Example:
REST API Characteristics (Constraints)
For an API to be truly “RESTful”, it must adhere to specific architectural constraints:
- Client-Server Architecture: Separation of concerns. Client and server can evolve independently without breaking the interface.
- Stateless Operations: Each API exchange is a completely independent event. The server does not store session state or information about previous requests. If authentication is required, credentials/tokens must be sent with every single request.
- Misconception: TCP (Layer 4) is stateful, but HTTP/REST (Layer 7) is stateless. Layer functions are separate.
- Cacheable: APIs must support caching to improve client performance and reduce server load. Resources must be explicitly declared as cacheable or non-cacheable by the server.
- Uniform Interface: Standardized way of communicating (e.g., using standard HTTP verbs).
- Layered System: Client cannot ordinarily tell whether it is connected directly to the end server or an intermediary.
- Code-on-Demand (Optional): Servers can temporarily extend client functionality by transferring executable code.
REST API Authentication Methods
Authentication validates the identity of a user/system to ensure legitimate access to resources. Always use HTTPS (HTTP + TLS encryption) to protect credentials in transit.
1. Basic Authentication
- Concept: Sends a username and password with every request.
- Format: Included in the
Authorizationheader, encoded in Base64 format (e.g.,Authorization: Basic amVyZW15OmNjbmE=). - Pros: Simple and easy to implement.
- Cons: Base64 is encoding, NOT encryption. It is easily decoded. If intercepted without HTTPS, credentials are compromised.
2. Bearer Authentication (Token-Based)
- Concept: Client first authenticates with an Authorization Server to obtain a temporary Bearer Token. This token is then included in the
Authorizationheader of subsequent requests (e.g.,Authorization: Bearer <token>). - Pros: More secure than Basic Auth; credentials are not sent repeatedly. Tokens expire, limiting the window of vulnerability.
- Cons: If a token is stolen, the attacker has full access until it expires. Requires token refresh logic.
3. API Key Authentication
- Concept: Uses a static, unique key issued by the API provider to identify the client and track usage/billing.
- Format: Best practice is to include it in the
Authorizationheader (e.g.,Authorization: ApiKey <key>). - Pros: Excellent for tracking usage analytics and billing (e.g., third-party cloud APIs). Easier to implement than Bearer tokens.
- Cons: Does not expire automatically. If stolen, it grants access until manually revoked by the administrator.
- Misconception: Never put API keys in the URL path/query string. URLs are logged by browsers, proxies, and servers, exposing the key to attackers.
4. OAuth 2.0
- Concept: An advanced framework for access delegation. It allows third-party applications limited access to a user’s resources without sharing the user’s actual credentials (e.g., “Log in with Google”).
- Parties Involved:
- Resource Owner: The user/account owner granting access.
- Client App: The third-party application requesting access.
- Authorization Server: Issues access tokens after user approval (e.g., Google’s OAuth service).
- Resource Server: Hosts the protected data (e.g., Google Calendar data).
- Mechanism: Uses short-lived Access Tokens for API calls, and Refresh Tokens to silently obtain new access tokens without requiring the user to log in again.
Authentication Methods Comparison
| Feature | Basic Auth | Bearer Auth | API Key | OAuth 2.0 |
|---|---|---|---|---|
| Credential Type | Username/Password | Dynamic Token | Static Key | Access/Refresh Tokens |
| Expires Automatically? | No | Yes | No (Manual revocation) | Yes (Access token); Refresh token extends it |
| Primary Use Case | Simple internal tools | Modern user-facing APIs | Usage tracking, billing, machine-to-machine | Third-party delegated access (e.g., SSO) |
| Security Level | Low (relies entirely on HTTPS) | Medium-High | Medium | High |
Practical Example: Cisco DevNet DNA Center API
Below is the logical flow of retrieving a device inventory using Postman/HTTP:
Step 1: Obtain Authorization Token (POST)
POST https://sandboxdnac.cisco.com/dna/system/api/v1/auth/token
Headers:
Authorization: Basic ZGV2bmV0dXNlcjpDaXNjbzEyMyE=
Response: 200 OK with a JSON body containing the token value.
Step 2: Retrieve Device Inventory (GET)
GET https://sandboxdnac.cisco.com/dna/intent/api/v1/network-device
Headers:
X-Auth-Token: <paste_token_from_step_1_here>
Accept: application/json
Response: 200 OK with a JSON-formatted list of devices (e.g., hostname, platform ID like C9300-24U, role, uptime).
Commands and Syntax Reference Summary
# Standard HTTP Request Structure
<METHOD> <URI_PATH> <HTTP_VERSION>
Host: <AUTHORITY>
Accept: <MIME_TYPE>
Authorization: <SCHEME> <CREDENTIALS_OR_TOKEN>
<BLANK_LINE>
<MESSAGE_BODY>
# Common Headers
Accept: application/json
X-Auth-Token: <your_token_here>
Authorization: Basic <base64_string>
Authorization: Bearer <token_string>
# Common Status Codes to Memorize
200 OK
201 Created
403 Forbidden (Authentication/Authorization required)
404 Not Found
500 Internal Server Error
Things to note:
- Always differentiate between encoding (Base64, reversible, no security) and encryption (TLS/HTTPS, requires a key, provides security).
- REST is stateless. Do not confuse this with TCP, which is stateful. The application layer (REST/HTTP) treats every request as a new, independent transaction.