Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PostMan API

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Application Programming Interfaces

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 the sharing of
resources and services across applications, organizations, and devices.

Have you ever made a payment on a website? Checked the weather on a mobile app? Listen to
Spotify on both your desktop and your phone? Used Google Maps inside another app? Whether
you know it or not, you are using APIs every day. Even this lesson you are reading is brought to
you by an API!

Why are APIs important?


1. APIs help developers integrate exciting features and build
automations without reinventing the wheel
ex: using a Weather API instead of launching your own weather
balloons

2. APIs allow enterprises to open their product for faster innovation


ex: apps that interact with Twitter or Meta APIs by posting on
your behalf or reading tweets

3. APIs can be products themselves


ex: Software as a Service (SaaS) products like Stripe's payment
APIs or Twilio's text messaging and email APIs
A customer who wants soup doesn’t go into the kitchen to cook. They don't even have to know
how to make soup! They only must know how to ask the waiter for soup and expect the waiter
will bring back soup.

APIs work the same way, but there are different names for the players involved. Instead of soup,
the requester might ask for data or execution of a service.

Networking
Description Restaurant analogy
term
The requester. Ex: browser, web
Client Customer
app, mobile app
Simplified interface for
API Waiter
interacting with the backend
The backend where the
Server Kitchen
processing happens

 Hardware APIs
Interface for software to talk to hardware.
Example: How your phone's camera talks to the operating
system.

 Software Library APIs


Interface for directly consuming code from another code base.
Example: Using methods from a library you import into your
application.

 Web APIs
Interface for communicating across code bases over a network.
Example: Fetching current stock prices from a finance API over
the internet.
Multiple API types may be used to achieve a task. For example, uploading a photo to Instagram
makes use of various APIs:
4. Hardware API for the app to talk to your camera

5. Software library API for the image to be processed with filters

6. Web API for sending your image to Instagram's servers so your


friends can like it!

Architectures
There is more than one way to build and consume APIs. Some architecture types you may come
across are:

 REST (Representational State Transfer)


 GraphQL
 WebSockets
 webhooks
 SOAP (Simple Object Access Protocol)
 gRPC (Google Remote Procedure Call)
 MQTT (MQ Telemetry Transport)

Don't worry about knowing all of these! We will focus on REST APIs in this course since this
is the most widely adopted API architecture.

REST APIs
Some traits of REST APIs include not storing session state between requests, the ability to
cache, and ability to send and receive various data types. Still confused? Don't worry, we
will learn hands-on very soon in this course!

Accessibility
APIs also vary in the scope of who can access them.
 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 relation

Working with APIs then and now: cURL vs Postman


Before Postman, it was common practice to poke at APIs with a command line tool for making
HTTP requests called cURL. This tool is still used today, but has its limitations when it comes to
collaboration and sharing.

API calls with curl


This is an example of what an API call in the terminal using the curl
command looks like. Here we are fetching data about GitHub user postmanlabs

View the response


If everything goes well, you will see a response from the server in the lower half of Postman.

It should look something like this: a JSON (JavaScript Object Notation) response body that is an
array of book objects. You can scroll down to see more books.
You might see different books because this is a public library being modified in real time by
other Postman librarians around the world!
Request methods
When we make an HTTP call to a server, we specify a request method that indicates the type of
operation we are about to perform. These are also called HTTP verbs.

Here are some common HTTP request methods that correspond to the CRUD operations
mentioned earlier. You can see a list of more methods here.

Method name Operation

GET Retrieve data (Read)

POST Send data (Create)


Update data (Update)

PUT/PATCH * PUT usually replaces an entire


resource, whereas PATCH usually is for
partial updates
DELETE Delete data (Delete)

Since we are "getting" books and not modifying any data, it makes sense that we are making a
GET request.

These are just conventions - it all depends on how the API is coded. To know which method to
use, always read the documentation for the API you're working with! (Postman Library API v2
docs)

Request URL
In addition to a request method, a request must include a request URL that indicates where to
make the API call. A request URL has three parts: a protocol (such as http:// or https://),
host (location of the server), and path (route on the server). In REST APIs, the path often points
to a reference entity, like "books".

Protocol Host Path


https:// library-api.postmanlabs.com /books
Paths and full URLs are also sometimes called API endpoints.
Response status codes
The Postman Library API v2 has sent back a response status code of "200 OK". Status codes
are indicators of whether a request failed or succeeded.

Status codes have conventions. For example, any status code starting with a "2xx" (a "200-level
response") represents a successful call. Get familiar with other status code categories:

Code range Meaning Example


200 - OK
201 - Created
2xx Success
204 - No content (silent
OK)
301 - Moved (path
changed)
3xx Redirection

400 - Bad request


401 - Unauthorized
4xx Client error
403 - Not permitted
404 - Not found
500 - Internal server error
5xx Server error 502 - Bad gateway
504 - Gateway timeout

That's a lot to remember! Have no fear - in Postman you can hover on any response code to see
what it means.

Request-Response pattern
Now you can understand the request response pattern, which represents how computers
communicate over a network. An API is the interface that lets us know what kind of response to
expect when we make certain calls to a server.

You made an HTTP GET request to https://library-api.postmanlabs.com/books and


received a response from the 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.

That's it!

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 photos to be returned:

GET https://some-api.com/photos?orientation=landscape&size=500x400

Search Google - with query parameters!


Try pasting this URL into your browser or as a GET request in Postman to make a Google search
for "postman". (If you use Postman, click the "Preview" tab in the response to view the rendered
HTML!)
https://www.google.com/search?q=postman

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.

Because this parameter is in our request, the server returns an HTML document that is a search
results page with hits for "postman". The search bar is pre-populated with our query "postman".

You can change your search directly from the URL by changing the value for the query
parameter q=<something else!>

When to use query parameters?


The answer is always: read the API documentation!

Sometimes query parameters are optional and allow you to add filters or extra data to your
responses. Sometimes they are required in order for the server to process your request. APIs are
implemented differently to fulfill different needs.

The Postman Library API v2 allows you to add optional query parameters on requests to GET
/books to filter the books that come back in response. Let's try it out next!

Let's try to filter our books results to only show us fiction books. Check out the Postman Library
API v2 documentation!

The API allows us to add query parameters to a GET /books request to filter the results, as
shown under "Params"
Using the Params tab, add a query parameter with key genre and value
fiction to the "get fiction books" request. Notice how Postman syncs
the request URL in real time, adding the question mark ? automatically
to mark the start of query parameters!
Path Parameters
Another way of passing request data to an API is via path parameters. A path parameter (or
"path variable") is a dynamic section of a path, and is often used for IDs and entity names such
as usernames.

Path parameter syntax


Path parameters come immediately after a slash in the path. For example, the GitHub API allows
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 {username} will fetch data about that user:

GET https://api.github.com/users/postmanlabs

You can have multiple path parameters 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


At first it is easy to confuse these two parameter types. Let's compare them side by side.

Path parameters Query parameters


ex: /books?
ex: /books/abc123
search=borges&checkedOut=false

Located directly after a slash in the path. Can be Located only at the end of a path, right after a
anywhere in the path question mark ?
Accepts defined query keys with potentially
Accepts dynamic values
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 path parameters?


Always read the API documentation! If a path parameter is required, the documentation will
mention this.

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!

Next we will use path parameters with the Postman Library API v2 to get a specific book.

omeone keeps coming into the library every day asking whether "Ficciones" by Jorge Luis
Borges is available.

When you fetched all the books in the library, you may have noticed that each book as a unique
id value. This id can always be used to identify the book, even if its other properties are
changed.

Since this person keeps asking about "Ficciones", you've jotted down that the unique id for this
book is 29cd820f-82f9-4b45-a7f4-0924111b5b89

(Don't believe us? You can always search for "Ficciones" with the search query parameter: GET
/books?search=ficciones)
7. Save your request

8. Send your request


You should get a 200 OK response with a single JSON object that represents the "Ficciones"
book. At the time of this example, the book is not checked out:

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 (password-less authorization), and API Keys (secret strings registered to
a developer from an API).

Getting an API Key


APIs that use API Key auth usually allow developers to sign up in a developer portal, where they
will receive a random API Key that can be used to authorize their requests to the API. The API
Key allows the API to track who is making calls and how often.

The Postman Library API v2 uses very light protection and does not require you to register for
an API Key. You simply have to know it:

Header name: api-key


Header value: postmanrulz

As the documentation shows, the Postman Library API v2 requires adding this header to any
requests for adding, updating and deleting books, since these operations actually change data in
the database as opposed to simply reading them.

Headers
Headers are how we can add metadata about our requests, such as authorization information or
specify the data type we want to receive in a response. This is different than the actual payload
data we send in the body of a request, such as our new book information.

You can think of headers like the outside of an envelope when you send a letter. The envelope
has information about delivering the letter, like proof that you've paid for postage. The actual
data "payload" is the letter inside the envelope.

You might also like