API Lab Guide Part 1 - API Basics

Corporate logotype

Estimated Time: 60 minutes.

Objective

Humans speak to humans, humans speak to machines, but how do machines speak to machines? Using APIs! The purpose of this lab is to help you understand what APIs are, the basics of how they work and why they are useful.

The Lab Journey

In this lab we are going to look at a few API basics that will set the foundations for future labs. We will cover:
  1. What an API is and why we use them

  2. Different API integrations

  3. Different API types

  4. An In-depth look at the RESTful API architecture

  5. HTTP REST verbs

  6. HTTP response codes

  7. Response payloads

If you are comfortable with RESTful APIs you may want to skip this lab.

1. What is an API?

An API, or Application Programming Interface, is a standardized way for different applications, systems, and devices to share data and information with each other. The Apstra API allows customers to interact with it by asking it questions or telling it to do something. For example, a customer might ask the Apstra API for information about deployed switches, or instruct it to create a new VRF. This interaction follows a client-server model, where the client (such as a script, ticketing system, or command line window) initiates the request and the server (in this case, the Apstra API) responds with the requested information. Essentially, the API serves as a communication channel between the client and the server.

API in human speak

2. Why use APIs?

There are two main reasons why APIs are commonly used in the real world:

  1. Integration with internal and external systems: APIs allow different applications, systems, and devices to communicate with each other and share data, making it easier to integrate them into a larger system. This can be useful for things like connecting a CRM system to an accounting system, or integrating a network management tool with a monitoring system.

  2. Automating tasks: APIs can be used to automate tasks that would normally require a user to interact with a graphical user interface (GUI). For example, an API could be used to automate the process of provisioning a new user account or creating a report. This can save time and reduce the risk of errors.

Overall, APIs are used to facilitate communication and integration between different systems, and to automate tasks that would otherwise require manual intervention.

Integration with other systems

In an organization, there may be multiple systems that are used to manage the network, such as a ticket management system, an IP address management tool, or an analytics collector. By using the Apstra API, these systems can be integrated to create a more streamlined, automated network management experience. For example, suppose you want to open a ticket to deploy a VRF that will support a new business application. By integrating the ticket management system and Apstra via their APIs, you can create a program that automatically triggers the creation of the VRF when the ticket is opened, saving time and eliminating the need for manual intervention. This is just one example of how APIs can be used to facilitate communication and integration between different systems, improving efficiency and automating tasks.

Check out this recording of a previous Network Field Day where Apstra, Service Now and Slack were integrated to deploy and monitor data centers.

Automating GUI based tasks

Adding a new virtual network (VXLAN) in a data center can be a time-consuming task, especially if you have to do it multiple times. Using the Apstra web interface, it might take an engineer around 60 seconds to add a single virtual network. However, if you need to add 1000 virtual networks for a tenant, this task becomes much more tedious and prone to errors. This is not because people are incapable of doing it, but rather because humans can get distracted, tired, or complacent when performing repetitive tasks.

On the other hand, computers are very good at executing tasks over and over with 100% accuracy. By using a simple script and the Apstra API, a network administrator could create thousands of virtual networks in just a few seconds. This not only saves time, but also ensures that the virtual networks are created correctly, without any errors.

To calculate the time saved using this approach, we can do the following calculation: 60 seconds x 1000 virtual networks = 1000 minutes minutes, which is nearly 17 hours of time saved. If you need to perform this task once a month, the time savings really start to add up. Overall, using APIs and automation can greatly improve efficiency and reduce the risk of errors when performing tasks in a data center.

3. Different API Types

There are several different types of APIs, each with its own characteristics and uses. Some of the most popular API architectural styles include:

  1. REST API: A REST (REpresentational State Transfer) API is a type of API that relies on a few guiding principles, such as a client-server architecture and simple, uniform interfaces, to communicate between systems. REST APIs are very common in modern applications and are designed to be easy to use and flexible.

  2. Webhooks: A webhook is an event-based API that allows one system to send messages to another system anytime a particular event occurs. Unlike REST APIs, which require the client to initiate communication, webhooks are initiated by the server and are often referred to as "reverse APIs." Webhooks are commonly used in continuous integration and delivery (CI/CD) workflows and cloud SaaS applications.

  3. SOAP API: A SOAP (Simple Object Access Protocol) API is a more structured and formalized API that uses an XML-based messaging protocol with Envelope, Header, and Body tags. SOAP APIs are reliable and trusted, but can be slower than other types of APIs. While most modern applications have moved away from using SOAP-based APIs, there are still many legacy API implementations that use SOAP.

4. RESTful APIs

Apstra uses a REST (REpresentational State Transfer) API, which is an architectural style for delivering APIs that is based on the HTTP specification used by the web. It’s important to note that REST is a style, rather than a standard, and it is made up of different standards such as HTTP, XML, URL, and JSON.

REST APIs use URLs (uniform resource locators) to make data available, and they rely on HTTP methods, headers, and other building blocks to facilitate communication between systems. One of the benefits of REST APIs is that they are simple and widely recognized, making them a common starting point for teams when they are first learning about APIs. In contrast, SOAP APIs are more structured and formalized, and may require more setup and configuration.

To interact with a resource using a REST API, you need to use a URL to specify the resource you want to access and an HTTP method to indicate the type of request you are making. The four main HTTP methods used in REST APIs are:

  1. GET: The GET method allows you to retrieve an object or data from the server. When you make a GET request, the server sends the requested object back to you in the form of a response.

  2. POST: The POST method tells the server to create a new object. This object may have parameters that need to be specified in the request.

  3. PUT: The PUT method tells the server to update an existing object.

  4. DELETE: The DELETE method tells the server to delete one or more entries from the system.

These HTTP methods correspond to the common CRUD (create, read, update, delete) operations that are often used in computing. By using the appropriate method, you can perform a wide range of actions on resources using a REST API.

The diagram below illustrates the flow of the four main HTTP methods used in REST APIs: GET, POST, PUT, and DELETE. These methods allow you to perform a variety of actions on resources, such as retrieving data, creating new objects, updating existing objects, and deleting entries.

API Basic Methods

In the following sections, we will go into more detail about the key components of RESTful API calls, including the URL, the HTTP method, and the parameters that may be included in the request.

4.1. HTTP Header and Body

When two systems communicate using a RESTful API, there is a request and response process. The client sends a request to the server, and the server sends a response back to the client. Both the request and the response consist of a HTTP header and a HTTP body. The header contains information about the request or response, such as the type of content being sent and the status of the request. The body contains the actual content being sent, such as data or parameters. By following this request-response process, the client and server can communicate and exchange information using RESTful APIs.

API in human speak

4.1.1. HTTP Headers

HTTP headers are used to send additional information with an HTTP request or response. They can be thought of as "meta-data" for your API calls, as they contain information such as API tokens, caching details, and the type of content being sent in the body of the request or response. By including this information in the header, the client and server can pass along additional details about the request or response, helping to facilitate communication between the two systems.

4.1.2. HTTP Body

The HTTP body is the part of an HTTP request or response that contains the actual content being sent. For example, if you make a POST request to Apstra asking it to create a new VRF, the HTTP body will contain the necessary information about the VRF, such as its name and any other relevant details. In general, the HTTP body is used to include information that is relevant to the API call being made, and it can be in a variety of formats such as text, JSON, or XML.

4.2. HTTP Methods

The table below describes five of the common API methods you’ll come across in the Apstra API. This section does omit the HEAD, OPTIONS and TRACE methods, but you can read about these elsewhere.

Idempotency refers to the property of an action or operation that produces the same result regardless of how many times it is performed. In the context of APIs, this means that if you make the same request multiple times, you will receive the same response. For a RESTful service, this means that clients can make repeated calls to the same endpoint without changing the overall result. However, it’s important to note that while the result on the server may be the same, the actual response may not be identical (e.g., a resource’s state may have changed between requests). This is because idempotency only refers to the result of the operation, not the specifics of the response itself. Overall, idempotency is an important concept in API design, as it helps to ensure that operations are predictable and consistent, even if they are repeated multiple times.

HTTP Verb

CRUD

Description

GET

Read

The HTTP GET method is used to retrieve data or a representation of a resource. When you make a GET request, the server sends a response containing the requested data, along with a HTTP response code indicating the status of the request. If the request was successful, the response code will be 200 (OK). If there was an error, the response code may be 404 (NOT FOUND) or 400 (BAD REQUEST).

According to the HTTP specification, GET requests should only be used to read data, and not to change data. This makes GET requests safe, as they can be called without risking data modification or corruption. GET requests are also idempotent, which means that making multiple identical requests has the same effect as making a single request. In other words, calling a GET request once has the same result as calling it multiple times. These properties of GET requests make them useful for retrieving data from a server without altering it in any way.

POST

Create

The POST verb is typically used to create new resources. When you make a POST request, the server processes the request and creates a new resource. If the resource is created successfully, the server will return a HTTP response code of 201, along with a payload containing information about the new resource, such as its ID.

Unlike GET requests, POST requests are not safe or idempotent. This means that making two identical POST requests will likely result in the creation of two separate resources with the same information. This is because POST requests are used to create new resources, rather than simply reading or retrieving existing ones. As a result, POST requests can have unintended consequences if they are repeated, and they should be used with caution.

PUT

Update/Replace

The PUT verb is typically used to update existing resources. When you make a PUT request, you send a new representation of the resource, containing updated information. This means that while you are not creating a new resource, you are overwriting the existing information about it.

If a PUT request is successful, the server will return a HTTP response code of 200 (OK) or 204 (No Content). PUT requests are not safe, because they modify the state of a resource on the server. However, they are idempotent, which means that making multiple identical PUT requests has the same effect as making a single request. In other words, if you update a resource using PUT and then make the same request again, the resource will still exist and will have the same state as it did after the first request. This makes PUT requests useful for updating resources without affecting their overall state.

PATCH

Update/Modify

The PATCH verb is used to modify existing resources. When you make a PATCH request, you only need to send the changes that you want to make to the resource, rather than the complete resource itself. This allows you to make specific updates to a resource, rather than replacing it in its entirety. PATCH requests are typically used to make partial updates to a resource, rather than replacing it completely like a PUT request would. The server will process the request and apply the specified changes to the resource, and may return a response indicating the status of the request.

DELETE

Delete

The DELETE verb is used to delete a resource from the server. When you make a DELETE request, the server processes the request and removes the resource from the server. If the request is successful, the server will return a HTTP response code of 200 (OK) along with a response body, or a code of 204 (No Content) with no response body.

DELETE operations are typically idempotent, which means that making multiple identical DELETE requests has the same effect as making a single request. In other words, if you delete a resource using DELETE and then make the same request again, the resource will still be gone. However, it’s worth noting that the response code for the first DELETE operation may be different from subsequent operations. Overall, DELETE is a straightforward and easy-to-understand verb that is used to remove resources from the server.

4.3. Status Codes

HTTP response status codes are used to indicate the status of an HTTP request. They provide information about whether the request was successful or not, and if not, they give some insight into what went wrong. There are five main categories of HTTP status codes:

1xx Informational responses: These codes indicate that the request was received and is being processed. 2xx Successful responses: These codes indicate that the request was received, understood, and accepted. 3xx Redirection responses: These codes indicate that further action is required to complete the request. 4xx Client error responses: These codes indicate that there is a problem with the request, such as bad syntax or an inability to fulfill it. 5xx Server error responses: These codes indicate that the server failed to fulfill an apparently valid request. Understanding HTTP response status codes is important for understanding the results of API requests and determining how to handle any errors that may occur.

All HTTP status codes are well documented so when in doubt, Google!

The table below shows some of the most common HTTP status codes you are likely to come across.

CODE

TYPE

Description

200

OK

General success status code. This is the most common response code. Used to indicate success.

201

CREATED

If a POST or PUT request is successful, it means that a new resource has been created or an existing resource has been updated. The server should return a HTTP response code of 201 (Created) and may include a Location header with a link to the newly-created resource. The response body may or may not contain additional information about the resource. These verbs are not idempotent.

204

NO CONTENT

The HTTP response code 204 (No Content) indicates a successful request with no additional information to provide in the response body. This status code is often used in DELETE and PUT operations. It does not indicate an error.

400

BAD REQUEST

General error for when fulfilling the request would cause an invalid state. Domain validation errors, missing data, etc. are some examples.

401

UNAUTHORIZED

Error code response for missing or invalid authentication token.

403

FORBIDDEN

Error code for when the user is not authorized to perform the operation or the resource is unavailable for some reason (e.g. time constraints, etc.).

404

NOT FOUND

Used when the requested resource is not found, whether it doesn’t exist or if there was a 401 or 403 that, for security reasons, the service wants to mask.

500

INTERNAL SERVER ERROR

Never returned intentionally. The general catch-all error is when the server-side throws an exception. Use this only for errors that the consumer cannot address from their end.

5. API Returned Data

You have made an API call, the server understood your request and now some data is returned!

Responses from an API call are typically returned in either JSON or XML. Apstra like most modern REST APIs returns data in the JSON format. JSON is a whole large subject we will not delve deep into, but you can use this guide as a reference. Another useful tool is an Online JSON formatter/validator to review and decipher API returned data.

When you make an API call, the server receives your request and processes it. If the request is successful, the server will typically return data in response to your request. This data is often returned in either the JSON (JavaScript Object Notation) or XML (Extensible Markup Language) format. Apstra, like many modern REST APIs, uses the JSON format to return data. JSON is a widely used data interchange format that is easy to read and write and can be easily parsed by computers. You can use online resources such as the Mozilla Developer Network or a JSON formatter tool to help understand and interpret JSON data returned from an API.

5.1. Example API Request/Response

This section is just to give an idea of what a simple API request and response look like. If you would like to try this out yourself, REQBIN have a useful tool.

This section is meant to give you an idea of what a simple API request and response look like. If you want to try making API requests yourself, REQBIN offers a useful tool that you can use.

5.1.1. Example POST Request From A Client

You’ll notice in this example we are creating (POST) a transaction for John Smith.

POST /echo/post/json HTTP/1.1
Authorization: Bearer {token}
Host: reqbin.com
Content-Type: application/json
Content-Length: 80

{
  "Id": 12345,
  "Customer": "John Smith",
  "Quantity": 1,
  "Price": 10.00
}

5.2. Example Response From A Server

And the relpy is simply a response of {"success":"true"} and a Status code of 200 OK showing that the request was executed successfully.

HTTP/1.1 200 OK
Date: Tue, 24 Nov 2020 06:17:50 GMT
Content-Type: application/json
Content-Length: 19


{"success":"true"}

6. Tools to make API calls

One missing part of the API puzzel, how do you actually make API request to Apstra or any other system as a user. There are several API clients that can be used and a few options are shown below.

cURL

cURL is a command-line tool that is used to transfer data, including making requests to API endpoints. It is a free, open-source software project that can be found at https://curl.se/.

There are several reasons why you might choose to use cURL:

  1. It is highly portable and can be used on almost any operating system or connected device.

  2. It is useful for interacting with endpoints and testing API functionality.

  3. It can be verbose, providing detailed information about what has been sent and received, which is helpful for debugging and learning.

Below is an example of a simple cURL request.

curl --location --request POST 'https://apstra-vm.net/api/api/user/login' \
--header 'Content-Type: application/json' \
--data-raw '{
  "username": "admin",
  "password": "admin"
}'

Python

In order to work with APIs in Python, you will need tools that will make those requests. In Python, the most common library for making requests and working with APIs is the requests library. The requests library isn’t part of the standard Python library, so you’ll need to install it to get started.

Using a programming langue such as Python is a great way of creating more complex API workflows where several requests are chained together to reach a certain outcome.

Below is an example of a simple request in Python. The result of running this small script would be Python printing the returned data to the console window.

import requests
import json

url = "https://apstra-vm.net/api/api/user/login"

payload = json.dumps({
  "username": "admin",
  "password": "admin"
})
headers = {
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

Postman

Postman is a graphical user interface (GUI) based API client that simplifies the process of creating, sharing, testing, and documenting API requests. It is available for multiple platforms and can be downloaded for free. Postman is a useful tool for learning APIs, and Juniper Apstra maintains a public Postman workspace to showcase what can be achieved with the Apstra API.

Postman is freely available on multiple platforms and can be downloaded here.

Below is an example of the Postmna UI interface with a request and a response.

Postman UI

7. Summary

That’s the end of the lab! By completing this lab, you should now have a general understanding of APIs and why they are used. You should also know that the Apstra API can be a powerful tool for automating tasks and integrating with other systems. In the next lab, we will focus on API authentication and making API calls to Apstra.