You’ve probably heard the term API (application program interface) used more than a few times, but do you really understand what an API is, what it does, and how it works? In this article, we dissect the term and examine the many various aspects of an API call.
What is an API?
An API is software that communicates with other software and typically provides some sort of service. A simple example is an application that takes in zip codes and returns city and state information. The API client (the user) asks the server for the information by passing in the zip code as a parameter. The server accepts the call and returns the requested data.
An API is about efficiency
Imagine that you have a headache. To stop your headache, you needed a pain reliever. You know others have developed pain relievers that could help with your headache, but instead, you have to create your own version of the drug. It doesn’t make sense. Does it? Why spend all that time and effort to make your own version of a drug, when so many others have already done it? Without APIs, software development is a bit like that.
The sharing or reuse problem has plagued software development for a very long time. Why should a developer need to write a new zip code utility program every time they need one when the post office offers one for free? By using an API, the developer doesn’t have to write the extra code, nor do they have to update the code every time there is a change in the zip code system. Because the developer doesn’t need to write or maintain the code, they can work directly on the code unique to their application.
API implementation
How a publisher chooses to implement an API is nobody’s business. That’s right. The client doesn’t care what happens beyond the interface. When you put a quarter into a gumball machine, do you care how the machine distributes the gumball to the chute? Probably not as long as you get your gumball. The coding languages, databases, and operating systems the API uses doesn’t matter to the client—that’s the beauty of an API. What does matter is the interface.
Don’t break the interface
The systems behind the interface can change completely, but the interface needs to stay the same. Once published, the publisher is careful only to add optional parameters to an interface. Changes to an API call’s required parameters “break” the interface. For example, if the zip code API’s interface initially took a five-digit zip code suddenly required the four-digit extension too, the change breaks the interface. Due to the change in the interface, every application that used the old interface no longer works. To solve this problem, the API publisher can do several different things:
- accept the four-digit parameter using an optional parameter.
- accept both five- and nine-digit zip codes handling the changes behind the scenes.
- expand the API to include a new call that takes a nine-digit look-up option leaving the original API call alone.
One of the most important tools you can have for any API is the API documentation. The documentation is key to understanding the interface. The publisher may provide static API documentation (view Uptrends’ MonitorCheck API static documentation) or interactive documentation in a product such as Swagger (view Uptrends’ API in Swagger). We get into Swagger later, but the two important things to note here are one, you always start with the API’s documentation, and two, you keep it close for reference when coding and troubleshooting API issues.
Types of APIs
APIs come in all kinds of flavors depending on their purpose. To keep it simple, let’s consider just two API groups: web services and all the others.
All the others: libraries, frameworks, and remote APIs
Also called source code APIs, developers use these APIs within their source code to handle many routine tasks. For example, an ODBC (open database connectivity) is an API that establishes a connection between the application and the database management system. The API manages the interaction between the two systems no matter the database type, operating system, or location as long as the database is OBDC compliant (learn more about the various types of APIs).
APIs like API libraries and frameworks make for more robust software and electronics for several reasons:
- encourages code reuse
- speeds the development process
- allows the sharing of resources; for example, an app on your phone gets access to location services using an API
APIs have revolutionized the web and the Internet of things.
Web service APIs
Web services are APIs that perform tasks over the Internet. Just about every interaction you make online uses one or more web services:
- checking for reservation availability
- processing a credit card transaction
- pulling current product information from a vendor’s catalog
- uploading/downloading images from social media
- getting directions through a navigation app
The list goes on and on and includes a lot of functionality that we never think about. For example, status updates from your smart appliances, your car’s navigation system contacting Google Maps to get and give current traffic conditions, and your smart TV accessing the API of a streaming service like Netflix.
Dissecting a web service API Call
Most commonly, web services use REST API (Representational State Transfer Application Program Interface) architectural style. A Web service that conforms to the REST API style is known as “RESTful.” REST doesn’t dictate language or operating system; instead, it just defines the principles of design to which an API must conform to declare itself RESTful. Learn more about RESTful APIs. The examples that follow use a RESTful architectural style.
RESTful APIs use HTTP
RESTful APIs communicate using HTTP/HTTPS the same as web browsers do, and a call to an API looks very much the same as the URL to access a webpage. For example, the call to Uptrends’ API to get the full list of checkpoints and their IP addresses is
https://api.uptrends.com/v4/Checkpoint
The URL to view the same data as a webpage is
https://www.uptrends.com/checkpoints
The latter results in a web page and the former returns a JavaScript Object Notation (JSON) or XML result.
The HTTP verbs
The HTTP methods or verbs define the action needed. Although you can find more HTTP request methods, we focus on five of the most widely used methods.
- GET
The GET request method retrieves something from a resource. For example, in our Checkpoint example above, the API call results in a list. However, it could also request a file, status, script, or any other digital resource. - POST
The POST request method sends data (and files) to the resource. For example, a POST may instruct the resource to do many things, such as update a shopping cart, create an account, make a reservation, or update social media. - PUT
The PUT request method is like a POST in that it asks to have the resource updated or created. However, replicating a POST request doesn’t do anything at all, which is to say it is idempotent. For example, with a POST, it is possible for the request to happen twice when a user clicks a submit button a second time. By using PUT, you can avoid duplicate customer orders. A PUT requires the request to include a URI (uniform resource identifier) that uniquely identifies the resource needing to be updated. If the resource already exists, PUT makes the modifications, and if the resource doesn’t exist, PUT creates the object with that URI. - PATCH
A PATCH is a partial change or update to a resource. With a PUT or a POST, you send the entire resource every time, but with a PATCH, you can send only the updates. - DELETE
Like it sounds, a DELETE request removes an entire resource. The server decides on how it handles the DELETE request and may not actually remove the resource.
HTTP request and response
As you probably already know, an HTTP request is when the client asks something of the server, and the response is the answer sent back from the host. The response may include data or just a result code. Both the request and response use the following format:
- Request Line
The request line from the client specifies the HTTP verb, the request URI, and the HTTP version.
The response also has a “request line” but this request line has the HTTP version and response code. - Headers
HTTP uses headers to pass additional information using a name/value pair. The request may have many header rows, such as host, date/time, connection information, content type information, content size, and cache settings. - Empty line
An empty line signifies the end of the headers and the beginning of the message body. - Message body
GET and DELETE requests don’t need the optional message body, but for other requests, the message body contains the data (if any) the server or client needs.
Let’s look at a couple of examples:
Sample request
The following request is for Uptrends’ checkpoint API. As you can see in the code below, you first have the request line with the verb, URI, and the protocol version. The second line, the host header, gives the domain name for the server. The third line, the accept header, tells the API to respond with JSON code. The fourth line is the authorization header that gives the encoded basic authentication details.
GET /v4/checkpoint/202 HTTP1.1
Host: api.uptrends.com
Accept: application/json
Authorization: Basic bWjIxOEBNd2ljajb206MRnNjkzNAGFlbEB1cHRyZW5kcy5==
GET https://api.uptrends.com/v4/checkpoint/202
You may see both formats used when reviewing request headers.
Sample response
The first line in the API response is the protocol version and the result code. The headers in the response tell the browser information about the response, such as how long the content can remain in the cache, the type of content, date/time, and content length. After the headers is a blank line followed by the message body. The message body contains JSON code (as instructed in the request), but XML is also available.
HTTP/1.1 200 OK
access-control-expose-headers: Request-Context
cache-control: no-cache
content-length: 63823
content-type: application/json
date: Thu, 03 Sep 2020 20:41:47 GMT
expires: -1
pragma: no-cache
referrer-policy: same-origin
request-context: appId=cid-v1:fa5a4436-5708-4a19-90fb-5e2623304195
{
"Data": {
"Id": 202,
"Type": "Checkpoint",
"Attributes": {
"CheckpointName": "Aalsmeer",
"Code": "AAL1",
"Ipv4Addresses": [
"213.214.121.213",
"185.113.196.214"
],
"IpV6Addresses": [
{
"IpAddress": "2a02:2858:201:4e::5",
"IsNative": true
},
{
"IpAddress": "2a02:2858:401:1::214",
"IsNative": true
}
],
"IsPrimaryCheckpoint": true,
"SupportsIpv6": true,
"HasHighAvailability": false
},
"Links": {
"Self": "/Checkpoint/221"
}
},
"Links": {
"Self": "/Checkpoint/221"
}
}
The above example requests information about one specific checkpoint. However, a previous call using a different URI retrieved the checkpoint ID used in this example. Some API calls stand alone, but many calls are part of a larger API exchange.
Tools for testing API calls
There are many free and paid tools available that allow you to make and test API calls. Two popular tools are cURL and Swagger UI. Another popular tool we will not discuss here is Postman.
cURL
Probably the most widely used tool is cURL. The “c” stands for command line, and the URL part stands for universal resource locator. The tool makes it possible to send and receive data from the command line, and HTTP is only one of the many supported protocols.
You probably have cURL already installed on your computer (if you’re using Unix or a Mac, you’ll find the tool preinstalled). To find out if your Windows machine has cURL installed, you can do a quick test.
- Open a command window (you can type “cmd” into the search box to find cmd.exe).
- Type
curl https://www.uptrends.com
at the command prompt. - Press Enter.
The result (see figure below) is the Uptrends websites’ HTML code. By using cURL notation, you can add headers to your API requests. Learn more about using cURL and get the download on the official website. You can also download the free e-book, Everything curl.
Test API calls using Swagger
Swagger is a visual documentation tool that allows developers and users to interact directly with your API without having an infrastructure in place. If the API you’re considering employing has an OpenAPI Specification, you’re in business. Uptrends has an OpenAPI Specification setup for version four of the API to use if you have an active Uptrends account.
How do I use Uptrends’ OpenAPI Specification?
If you have an Uptrends login, you can use the Uptrends Swagger page to interact with Uptrends API. In the following section, we do two things: Show you how to execute an API call using Swagger and get your API username and password.
The first thing you need to do is get your API credentials.
- Go to Uptrends API v4 Swagger documentation.
- Scroll down to Register and click to expand. You’ll notice many other calls along the way, but continue to Register. You can play with the others later.
- Click the green bar to view the API call documentation.
- Click Try it out to access the Execute button.
- Click Execute.
- Using your Uptrends credentials, complete the sign-in form on the pop-up window.
- Click Sign in.
- Note, the UserName and Password values returned in the response body. You’ll need these to access the API.
- Scroll to the top of the Swagger webpage.
- Click the green Authorize button.
- Use the username and password returned in the response body to complete the fields (you only need to complete the top section).
- Click Authorize.
- Click Close.
If not logged in, you’ll get authentication errors on your API call attempts. Play around with the various API calls (it is probably best to stick with GET requests). Notice the cURL syntax used to make the call (see the figure below). Swagger maintains your credentials with an encoded authorization header value.
Authorization header encoding
If you’re an Uptrends API user, and you use other means (such as scripts) to interact with the API, you may need to encode your API credentials. To encode your credentials, use base64 encoding on the username and password separated by a colon.
For example, the username and password
7341223ce90947cda53a66f67481908a:ipbI6+6wUXxlCYSTBUaCuuUyjTQYfNjM
becomes
NzM0MTIyM2NlOTA5NDdjZGE1M2E2NmY2NzQ4MTkwOGE6aXBiSTYrNndVWHhsQ1lTVEJVYUN1dVV5alRRWWZOak0=
with base64 encoding using a free online tool.
Conclusion
Hopefully, you’ve come away with a better understanding of web services and how they work. We encourage you to continue exploring the Uptrends API using Swagger, and you’ll notice that this information also comes in handy when setting up Multi-Step API Monitoring. If you have any questions about the API, we encourage you to explore our Knowledge Base or consult one of our support heroes.