API - the building block of modern systems
Authored by Debanjan Chakraborty
What is API?
An Application Programming Interface (API) is a contract that allows code to talk to other code. APIs are the building blocks of modern software because they allow for sharing of resources and services across applications, organizations, and devices.
APIs help developers integrate exciting features and build automation without reinventing the wheel
ex: using a Weather API instead of launching your weather balloonsAPIs allow enterprises to **open up their product for faster innovation
**ex: apps that interact with Twitter or Meta APIs by posting on your behalf or reading tweetsAPIs can be products themselves
ex: Software as a Service (SaaS) products like Stripe's payment APIs or Twilio's text messaging and email APIs
Who uses API's?
APIs are not just for developers. Non-developer roles, such as management, solutions architects, business and data analysts, educators and researchers also use API. All these roles benefit from the standardized data access provided by APIs.
APi is not only used in tech industries, business, IT, and banking sectors represent the bulk of API use, any industry can benefit from the convenience provided by APIs.
Important terms:
Client: The requester. Ex: browser, web app, mobile app
API: Simplified interface for interacting with the backend
Server: The backend where the processing happens
Taxonomy of API:
Based on Medium:
hardware API's:
- Interface for software to talk to hardware.
Example: How your phone's camera talks to the operating system.
- Interface for software to talk to hardware.
Software library API:
- Interface for directly consuming code from another code base.
Example: Using methods from a library you import into your application.
- Interface for directly consuming code from another code base.
Web API's:
- Interface for communicating across code bases over a network.
Example: Fetching current stock prices from a finance API over the internet.
- Interface for communicating across code bases over a network.
Architectures:
There are more than one way to build and consume Api's , some types of architectures are:
REST (Representational State Transfer)
GraphQL
WebSocket's
webhooks
SOAP (Simple Object Access Protocol)
gRPC (Google Remote Procedure Call)
MQTT (MQ Telemetry Transport)
We will mainly focus on REST Api's, some traits of REST APIs include not storing session state between requests, the ability to cache, and the ability to send and receive various data types. Still confused? Don't worry; we will learn hands-on very soon in this course!
Taxonomy based on scope of access:
**Public APIs (aka Open APIs)
**Consumed by anyone who discovers the API**Private APIs
**Consumed only within an organization and not made public**Partner APIs
**Consumed between one or more organizations that have an established relationship
API Platform:
It is a platform where we build and use API's.
The above image shows the overview of Api lifecycle and its surrounding ecosystem.
Request methods:
Method name | Operation |
GET | Retrieve data (Read) |
POST | Send data (Create) |
PUT/PATCH | Update data (Update), * PUT usually replaces an entire resource, whereas PATCH usually is for partial updates |
DELETE | Delete data (Delete) |
Request URL:
In addition to request method, there is a request URL, that indicates where to make the API call. A request URL has three parts:
Protocol | Host | Path |
https:// | library-api.postmanlabs.com | /books |
paths and complete URLs are also called API Endpoints.
Response status codes:
Status codes are indicators of whether a request failed or succeeded. They have conventions, for example any status code starting with a "2xx" (a "200-level response") represents a successful call.
Code range | Meaning | Example |
2xx | Success | 200 - OK |
201 - Created | ||
204 - No content (silent OK) | ||
3xx | Redirection | 301 - Moved (path changed) |
4xx | Client error | 400 - Bad request |
401 - Unauthorized | ||
403 - Not Permitted | ||
404 - Not Found | ||
5xx | Server error | 500 - Internal server error |
502 - Bad gateway | ||
504 - Gateway timeout |
The request response pattern represents on how computers communicate over the network, an API is an interface that lets us know what kind of response to expectwhen we make a certain calls to a server.
The client is the agent making a request. A client could be a browser or an application you have coded, for example. In our case Postman is the client because that's how we sent the request.
The request is sent over a network to some server. In our case, we made a request over the public internet to a server located at the address https://library-api.postmanlabs.com
.
The server interpreted the request (GET /books
) and sent the appropriate response over the network back to the Postman client: a list of books.
Query Parameters:
Remember that the minimum ingredients you need to make a request are:
a request method (
GET
/POST
/PUT
/PATCH
/DELETE
, etc)a request URL
Some APIs allow you to refine your request further with key-value pairs called query parameters.
Query parameter syntax:
Query parameters are added to the end of the path. They start with a question mark ?
, followed by the key-value pairs in the format: <key>=<value>
. For example, this request might fetch all photos that have landscape orientation:
GET
https://some-api.com/photos?orientation=landscape
If there are multiple query parameters, each is separated by an ampersand &
. Below two query parameters to specify the orientation and size of the photos to be returned:
GET
https://some-api.com/photos?orientation=landscape&size=500x400
For example, if you want to search google with search parameters:
here, this request adds a search term as a query parameter q=postman
("q" refers to "query" here) to the GET /search
path on Google's server.
When to use a search query?
The simple answer is; to read the API documentation properly so you can get information of the different types of query parameters that the API has.
Path variable:
Another way of passing request data to an API is via path variables (a.k.a. "path parameters"). A path variable is a dynamic section of a path and is often used for IDs and entity names such as usernames.
Path Variable Syntax:
The path variable comes immediately after a slash in the path. For example, the GitHub APIallows you to search for GitHub users by providing a username in the path in place of {username}
below:
GET
https://api.github.com/users/{username}
Making this API call with a value for {usernam
e}
will fetch data about that user:
GET
https://api.github.com/users/postmanlabs
You can have multiple path variables in a single request, such as this endpoint for getting a user's GitHub code repository:
GET
https://api.github.com/repos/{owner}/{repoName}
For example, to get information about the newman
code repository from postmanlabs
:
GET
https://api.github.com/repos/postmanlabs/newman
Path vs Query parameters:
Path Variable | Query parameters |
ex: /books/abc123 | ex: /books?search=borges&checkedOut=false |
Located directly after a slash in the path. It can be anywhere on the path | Located only at the end of a path, right after a question mark ? |
Accepts dynamic values | Accepts defined query keyswith potentially dynamic values. |
* Often used for IDs or entity names | * Often used for options and filters |
\ These are just conventions! Some APIs might ask you to pass an ID or username in a query parameter like this:*/users? Username=getpostman
When to use the path variable?
Same case as the query parameters that you have to read the API documentation carefully as it also contains the information about the path variables
Note that some API documentation uses colon syntax to represent a wildcard in the path like /users/:username
, while some use curly braces like /users/{username}
. They both mean the same thing: that part of the path is dynamic!
How to send POST request:
To make updates to the database, you need to send a post request to the database, this can be done using the body
You will need to send body data with requests whenever you need to add or update structured data. For example, if you're sending a request to add a new customer to a database, you might include the customer details in JSONdata format. Typically, you will use body data with PUT
, POST
, and PATCH
requests.
The Body tab in Postman enables you to specify the data you need to send with a request. You can send different types of body data to suit your API.
You can use raw body data to send anything you can enter as text. Use the raw tab, and the type dropdown list to indicate the format of your data (Text, JavaScript, JSON, HTML, or XML), and Postman will enable syntax-highlighting and appending the relevant headers to your request.
Now while sending the post request, you might get a 4xx series error(client side error), mostly a 401 unauthorized error, to solve this issue, you need an authorization key
Authorization:
Think about why you might not want an API to have completely open endpoints that anyone can access publicly. It would allow unauthorized people to access data they shouldn't see, or allow bots to flood an API with thousands of calls per second and shut it down.
There are multiple methods for authorizing a request. Some examples are Basic Auth (username and password), OAuth (delegated authorization), and API Keys (secret strings registered to a developer from an API portal).
upon successful adding of a reading, you get a 201-success message
Variables in Postman:
They are tools used to:
Reuse values to keep your work DRY(Don’t Repeat Yourself)
Hide sensitive values like API keys from being shared publicly
Scopes:
Mainly classified into global, collection, environment, data and local.
If a variable with the same name is declared in two different scopes, the value stored in the variable with narrowest scope will be used. For example, if there is a global variable named
username
and a local variable namedusername
, the local value will be used when the request runs.