Let’s get this party started with an introduction to APIs. We’ll start at the very beginning by asking “what is an API?”
Standing for Application Programming Interface, APIs are fundamental in the technology world around us.. You’re reading this article on TechBreakdowns.com and it was supplied to your browser using APIs provided by WordPress.com. When you go to Google, you’re using APIs, when you open up an app on your phone it communicates with servers using APIs. Even your thermostat is probably using APIs these days.
You can think of APIs as a waiter in a restaurant. You (the client) give your order (a request) to the waiter (the API). The waiter then goes to the kitchen (server) to get what you requested (data) and brings it back to you (the response).
In short, APIs are a set of rules that govern how software entities can communicate with each other. They define the methods and data formats that applications can use to request and exchange information.
Types of APIs
It’s worth bringing up here, early in the introduction, that there are a couple of types of APIs we should be aware of. First up are Web APIs.
Web APIs are accessible all over the web. When you click around the internet you’re interacting with APIs that are being communicated with over HTTP.
Local APIs are a little different, and they will not be the focal point of this article. Local APIs work in a similar way to Web APIs with the exception being they don’t communicate over the internet. The device you’re reading this on (be it a Mac, Windows, iOS, or Android) has APIs at the system level that run all the functionality you use.
Again, they act in a similar way to web APIs, but just aren’t as fun to talk about in an introductory way.
The Basics of APIs
At their very core, APIs make a request and they receive a response. The internet operates on what’s called a “client-server” model.
Your device (cell phone, web browser) is the client, this client sends a request to the server. The server then processes the request and sends the appropriate response back to your device.
If you open up the developer tools in a browser like Chrome you can actually see all of these requests happening as you click around the web. Above is a look at some of the API requests Twitter (I’m still not going to call it X) makes when loading the home page.
When building a web application, the most common things you’ll be allowing the user to do are:
- Create content (like a Tweet)
- Read content (like scrolling through Tweets)
- Update content (liking a Tweet, or even editing one)
- Delete content (oops, didn’t mean to Tweet that)
Those four activities are what’s known as CRUD. If you’ve been around technology for a while you’ve probably heard the phrase “CRUD app,” and that’s exactly what it’s referring to.
CRUD Maps to HTTP Methods
CRUD is “human” understandable. Even if you had never used a computer, you could figure out what’s going to happen if somebody used the terms create, read, update and delete.
Humans are cool and all, but machines require something different. In steps, at least on the web, HTTP methods.
HTTP stands for “Hypertext Transfer Protocol.” It is the foundation of data communication on the World Wide Web, defining how messages are formatted and transmitted, and how web servers and browsers should respond to various commands.
There are four primary HTTP methods, with a few others that are less commonly used:
- GET (READ): Used to retrieve data. When you visit a website, your browser is usually making a GET request to fetch the webpage.
- Example: Fetching a user’s profile.
- POST (CREATE): Used to send data to the server to create a new resource.
- Example: Signing up for a new account on a website.
- PUT (UPDATE): Used to update existing data or resources on the server.
- Example: Updating your profile information.
- DELETE (DELETE): As the name implies, it’s used to delete resources on the server.
- Example: Deleting an account or a specific post.
Less used, but you may come across them are PATCH, HEAD, OPTIONS, and TRACE. I’ve chosen to exclude the definitions.
Finally, Status Codes
When you make a GET request to your API for the weather, and it responds with ‘couldn’t find that location’ your weather app is mystified. It was expecting a list of temperatures, what is this bizarre string?
To alleviate potential miscommunication, APIs send a message, and a status code. Status codes convey meaning. In the above weather app example, an appropriate status code of
404 Not Found, or perhaps a
400 Bad Request would have let the app know that something isn’t quite right.
There are a number of predefined status codes. Software Engineers are also free to create their own status codes, but they’d have to make sure they documented what it actually means.
Status codes can be categorized as follows:
- 1XX -> Informational
- 2XX -> Successful
200 OK: standard response for successful requests
201 Created: the request was successful and a resource created
204 No Content: Successful, but an empty response
- 3XX -> Redirection
301 Moved Permanently: The URL of the requested resource has been changed permanently.
304 Not Modified: The resource has not been modified since the last request.
- 4XX -> Client Errors
400 Bad Request: The request could not be understood or was missing required parameters.
401 Unauthorized: Authentication failed or user doesn’t have permissions for the desired action.
403 Forbidden: Authentication succeeded, but the authenticated user doesn’t have access to the resource.
404 Not Found: The requested resource could not be found.
- 5XX -> Server Errors
500 Internal Server Error: Generic error message when an unexpected condition was encountered.
503 Service Unavailable: The server is not ready to handle the request, often due to maintenance or overload.
Different Types of APIS
There are three types of APIs that you should probably know about. What we’ve spoke about so far is called a REST API, and it’s what powers a majority of the internet.
REST APIs have advantages in scalability, flexibility, performance, and statefulness. They’re fairly easy to implement for CRUD like scenarios too, which is why they’re generally the goto.
Let’s take a look at something a little different though, SOAP APIs. These are definitely more obscure, but they’re worth hearing a bit about.
For the sake of simplicity, though, we’ll just hit on the high notes. I’ll write an article in the future about GraphQL as it really should get a standalone. SOAP, though, well a few notes are probably all you’ll need.
SOAP APIs are generally used in enterprise applications due to their strict standards and reliability features. You’ll also find them in banking / financial services environments, and at telecommunication providers. You’re unlikely to find SOAP APIs at a startup.
SOAP APIs use a communication language called XML. It looks very similar to HTML, and it’s not at all “clean” like the JSON that REST APIs use.
Still, there are some good parts about SOAP. It it very standardized, it has built in error handling, and it has functionality like
WS-ReliableMessaging which will ensure message delivery even if the network fails.
As you’re unlikely to ever build a SOAP API though in this, the year 2023, we’ll leave it at that.
GraphQL is something you are almost certainly going to see in a startup like environment. As I mentioned, we’ll keep it brief, but be on the lookout for a future GraphQL article.
GraphQL allows developers to create highly flexible APIs that use a single endpoint (one url). By using a single endpoint, GraphQL can offer efficiency advantages as developers can retrieve all the data they need in a single request.
It’s best suited to rapidly evolving applications, especially where the frontend is changing quickly. It’s also great for mobile applications as making a single request speeds things up where there might be network constraints.
API Design & Best Practices
While it’s highly unlikely you’ll be designing APIs if you’re not a software engineer or architect, it’s worthwhile to know what goes into the process. If you’re a Product Manager, a Designer, or any other occupation that works close with software creators, knowing this stuff could be a massive help.
First, endpoint design. If you read the last section, you’d have seen that GraphQL stands out by not requiring endpoint design. But, as we have been primarily focusing on REST, we’ll have to dive in.
When designing endpoints, two primary considerations to focus on are: naming conventions, and resource hierarchy.
When it comes to naming conventions, you’re looking to primarily use nouns, not verbs. It’s also normal, and natural, to use plural form, not singular – think
/users and not
From a hierarchy perspective, you’re going to want to consider how nesting will work. If we think of something like Twitter, you have a user and that user has Tweets. Because the Tweets are “owned” by a user, it makes sense to nest them in the resource hierarchy
Also worth considering, and something you’re going to want to keep a hold of over time, is consistency. Ensure that naming, parameter usage, and response formats are as consistent as possible across all endpoints. This will make things easier for new engineers joining your team, and make things easier for end-users if your API is accessible to them.
Initially, versioning might not seem crucial. However, within a year or as the API evolves, it can become vital. APIs are typically versioned with a
/v2/ in the URL. If you’re starting something fresh, it might be worthwhile doing this out the gate to save yourself some heartache in the future.
Rate limiting is worth considering in your API design, but it is something that can come later once you’re aware of a need.
Rate limiting prevents malicious or excessive use of your resources like someone scraping data, or even spamming users (depending on what your API does).
The most common ways of rate limiting include a fixed-window (ex. 1000 requests per hour) and a sliding window (ex. 1000 requests in any given 60 minute period). What you select will be entirely dependent upon how you expect the API to be used.
Authentication & Authorization
Last, and certainly not least is authentication & authorization. You’re probably going to want to limit who can use your API and this is typically done using API Keys, or using tokens.
API keys are more general in a server-to-server authentication situation, while external users are likely to be better served with a token-based approach.
After authentication, you’ll want to use scopes to limit what particular users can access.
Who doesn’t love cool tools?! Here are three tools I’ve used and liked in the past. Oh, and a bonus GraphQL tool in case you go down that path.
Swagger is a tool that auto-generates API documentation, allows for easy API testing, and more.
Really useful for internal and external APIs as it makes finding what engineers need a breeze.
Postman is used for API development and testing. Postman allows you to design, mock, debug, test, document and monitor APIs. The collaboration features are awesome and it has the ability to “mock” responses for testing/simulation before building out the API.
APImetrics is a decent monitoring solution that checks on your APIs from around the world. Provides insights into latency, uptime, and all that other cool stuff with really nice visualizations.
Apollo is a GraphQL “developer platform”, Apollo helps you develop, validate, and secure your GraphQL APIs. It has a good set of developer tools that offer insights into API performance and usage.
That’s a wrap on this API rundown. At right around 2,000 words I hope it has been both concise and useful for anyone looking to understand this cornerstone of the tech world.
Thanks for reading!
Glossary of Terms
Terms that were used in the article, organized here for ease of reference.
- API (Application Programming Interface): A set of rules and protocols that allows software applications to communicate with each other.
- Apollo: A platform for developing, validating, and securing GraphQL APIs.
- APImetrics: A monitoring tool that provides insights into API performance and usage from various global locations.
- Authentication: The process of verifying the identity of a user, system, or application.
- Authorization: The process of determining what an authenticated user or system is allowed to do or access.
- Client: In the client-server model, the client is the entity that sends requests and receives responses. Examples include web browsers or mobile apps.
- CRUD: Stands for Create, Read, Update, Delete. It refers to the four primary functions of persistent storage.
- Endpoint: A specific URL where an API can be accessed by a client application.
- GraphQL: A query language and server-side runtime for APIs that allows clients to request exactly the data they need.
- HTTP (Hypertext Transfer Protocol): The foundation of data communication on the World Wide Web.
- HTTP Methods: Standard methods or verbs used in HTTP requests to indicate the desired action to be performed.
- Local API: An API that operates on a local device or system, without the need for internet communication.
- Postman: A tool used for API development and testing.
- Rate Limiting: A strategy to control the number of requests a user or system can make to an API in a given time period.
- REST (Representational State Transfer): An architectural style for designing networked applications, commonly used in web APIs.
- Server: In the client-server model, the server is the entity that processes requests and sends responses back to the client.
- SOAP (Simple Object Access Protocol): A messaging protocol for exchanging structured information in the implementation of web services.
- Status Codes: Three-digit numbers returned by servers to indicate the status of a web request.
- Swagger (now known as OpenAPI): A tool for auto-generating API documentation and facilitating easy testing.
- Versioning: The practice of assigning unique versions to distinct stages of an API to ensure backward compatibility and clear communication of changes.
- Web API: An API that is accessed over the internet using HTTP or HTTPS.