Uploaded by Mitchell Francis

APIs Made Simpler by Darren Alderman 2

advertisement
Table of Contents
WHAT IS AN API?
3
Defining an API
3
An API in Action
4
JSON
5
Defining JSON
5
JSON Structure
6
JSON Simple Value Types
7
JSON Complex Value Types
8
Parsing JSON
9
Components of an API
11
API Foundations
11
Request Types
12
Query Parameters
13
Body
14
Headers
15
AmbleMind.com
2
WHAT IS AN API?
Defining an API
An Application Programming Interface (API) allows different apps,
websites, and databases to communicate with each other.
When an application creates an API, they define a set of agreements that
you can utilize to make requests to their application.
Each agreement contains:
1. Requirements for inputs
2. A description of what the application will do with those inputs
3. A promise that they will send you back a response. This response will
detail the data you requested or the changes the application made on
your behalf.
Most APIs follow the same standard set of rules. This makes it easier for APIs
to communicate with each other, and for you to use a multitude of APIs in
your application.
AmbleMind.com
3
An API in Action
Pull up a browser and go to https://placegoat.com/300.
PlaceGoat is a simple API that returns an image of a goat to use as a
placeholder. You might think it is just a link to an image, but you would be
wrong. Try refreshing the screen in a couple of different browsers.
If you go to https://placegoat.com/, you will see the API agreement they
make with you.
The agreement is: If you send a request to https://placegoat.com/ with the
‘width’ at the end, PlaceGoat will respond with a goat image with the
dimensions you requested.
Now, APIs are much more powerful than giving you goat images.
But before we can dive deeper, we must cover a crucial part of APIs: JSON
Let’s dive in.
AmbleMind.com
4
JSON
Defining JSON
JSON stands for JavaScript Object Notation.
JavaScript is the programming language that helps make web pages
dynamic. An Object is a group of related values stored together. So JSON is
JavaScript’s way of storing related values.
Because JavaScript and APIs are both so common and essential to
technology today. APIs often utilize the JavaScript Object Notation for
sending and receiving data.
Understanding JSON is essential to working with APIs.
So let’s dive into what JSON actually looks like, the structure it requires, and
how to use data from JSON in your app.
AmbleMind.com
5
JSON Structure
JSON is made up of property-value pairs. The property is the name of the
value. The value is the data.
It looks like this:
{
"key": "value",
"key2": "value2"
}
Take note of the following:
● { and } must start and close a JSON object.
● The property name is wrapped in quotation marks: "
● A : must follow the property and be before the value
● Multiple property-value pairs must be separated by a comma: ,
AmbleMind.com
6
JSON Simple Value Types
There are 4 basic JSON value types:
● Text (i.e. “this”) - This is a series of characters wrapped in quotation
marks. Think names, descriptions, email addresses, etc. Text values are
often referred to as Strings in the coding world.
● Numbers (i.e. 367) - Numbers can be negative (i.e. -12) or have decimal
values (i.e. 1.23), but they cannot have special characters like $ or %.
● True / False - True/False values are useful when asking questions. Like
“Is the phone number valid?” or “Is the user subscribed?” True/False
values are often referred to as Boolean values in the coding world.
● null - Null is a coding term for ‘there is nothing there’. This means the
value is empty and has not been set.
All together these 4 value types look like this in JSON:
{
"name": "Fred Flintstone",
"age": 47,
"favoriteApi": null,
"subscribed": false
}
Note: Only the text, "Fred Flintstone", is surrounded by quotations. If 47,
null, or false were in quotations, they would be treated as text values.
AmbleMind.com
7
JSON Complex Value Types
There are 2 “complex” value types in JSON that allow multiple values to be
grouped together.
The first is an Object. We have already covered what an object is, but what
you should understand here is that you can have a JSON object within
another JSON object. It looks like this:
{
"name": "Fred Flintstone",
"age": 47,
"spouse": {
"name": "Wilma Flinstone",
"female": true
}
}
The second complex type is an Array which is a list of values. The values can
be any of the types covered above including objects, but list should consist
of values of the same type. An array looks like this:
{
"name": "Fred Flintstone",
"children": [
"Pebbles",
"Rocky"
]
}
Note: The array is wrapped in [ and ]. The values in the array do not contain
properties. "children" is the property and it has multiple values.
AmbleMind.com
8
Parsing JSON
Parsing is a coding word for looking through some data to find and take out
the data you need. When an API returns JSON, you will need to “parse” the
JSON to grab the value(s) you are looking for.
The way you parse JSON depends on the platform or programming
language you are using, but all share the same concept.
In Javascript, the ‘.’ notation allows you to navigate to a property. If you need
to navigate an array you can use the ‘[#]’ notation. Here is an example:
{
"name": "Fred Flintstone",
"children": [
{
"name": "Pebbles",
"subscribed": true
},
{
"name": "Rock",
"subscribed": false
}
]
}
How would you get Fred Flintstone’s first child’s name?
let firstChildName = jsonObject.children[0].name
AmbleMind.com
9
NOTE: When JSON is transferred between APIs, it is sent as a string. This
means your computer will often read the JSON as a paragraph of text rather
than an object of properties and values. This means you may need to
transform the JSON text to be treated as a JSON object. This differs between
platforms and coding languages, but as an example, in javascript you
transform the JSON like this:
let jsonObject = JSON.parse(jsonString);
AmbleMind.com
10
Components of an API
API Foundations
When you go to a website, you type in a URL and then the internet does it’s
magic. It finds the webpage for that URL and returns it to you and displays it
on the screen.
APIs work in a similar manner. Every API has a URL. However, instead of a
webpage being returned, the API will send you data or messages.
Another key distinction of APIs is that you often tag along additional
parameters or components with the URL. These additional components
allow you to send data to the API, tell the API when you want to delete data
versus update data, and much more.
So let’s take a look at 5 components that are often utilized when working
with an API:
● Request Type
● Query Parameters
● Body
● Headers
● Authentication
AmbleMind.com
11
Request Types
When working with APIs, note that there are different types of requests.
Sometimes you will make an API call to get data and other times you may
want to delete data.
There are 5 request types I use on a regular basis:
● GET - Retrieves existing data. This is the most common API request.
You would use a GET request to retrieve a list of values to populate a
dropdown list.
● POST - Creates a new record. You would use a POST request when
adding a new profile, form submission, or task to a to do list.
● PUT - Replaces an existing record. You would use a PUT request when
updating a complete record. Think updating a profile on social media.
● PATCH - Replaces a subset of values in an existing record. This is
similar to POST, but only the values you specify are changed. Think
updating a status or checking off a to-do item.
● DELETE - Removes a record.
AmbleMind.com
12
Query Parameters
When sending an API call, you need to tell the API what records you want to
work with. Sometimes this is done in the URL itself. For example, in this
request I am telling the API the zipcode I want to receive data for in the URL
itself.
https://zipcodeapi.com/zip/11111/data
Other times, you pass in what are called Query Parameters. When you look
at the API’s documentation you want to use, it will specify any Query
Parameters it allows. Query Parameters are often used for sorting or filtering
the data returned.
Query Parameters are key-value pairs, but they do not follow JSON format.
Take a look at the following example:
https://api.mywebsite.com?key=value&key2=value2
Take note of the following:
● A ? indicates the start of query parameters.
● A & separates the 2 query parameters.
● Each query parameter is listed as the key, then =, then the value.
AmbleMind.com
13
Body
The Body of an API is used to send data. There are a few different formats
the data in the body can be in, but the format varies between APIs. A
common format to send data in is JSON format.
Now let’s start to get more comfortable working with APIs and their
documentation. Here is an example taken from the “Creating a resource”
section on this webpage: https://jsonplaceholder.typicode.com/guide/
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
...
In this JavaScript API call, you can see the URL for the API, the method (what
I call the request type), and finally the body.
This API call allows you to POST a new record, and we can see the body
should be in JSON format, and this JSON holds the data for the new record
that will be created:
{
title: 'foo',
body: 'bar',
userId: 1,
}
AmbleMind.com
14
Headers
Headers are additional properties that can be added to an API call to provide
additional context. Headers can communicate who is sending the API
request, where did it come from, what the API should respond with, etc.
Some headers are implied by default by the tool or coding language you are
using. Others will be specified in the API’s documentation.
A common header you will add is content-type. This tells the API what
format the data in the body is in.
If we take a look at the rest of the example noted above, you can see the API
requests that you set 'Content-type': 'application/json; in headers.
This confirms that the data in the body is indeed in JSON format.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
AmbleMind.com
15
Another common header parameter is Authorization which allows the API
to detect who is making an API request.
Authorization is important because it allows the API to prevent random
people from accessing or updating data they do not have access to.
Authorization also allows the API to enforce quotas. This is often used to
require high-volume users to pay money to use the API. This is the
“freemium” model of the API business. Small applications can use the API
for free, but once you get over 25,000 API calls a month, you’ll have to pay.
Let’s take a look at this Airtable API example from their documentation.
curl -v -X POST
https://api.airtable.com/v0/appKi1Rvx1swA9kCd/Journal%20Entries \
-H "Authorization: Bearer keytrcc12T45FGpoi" \
-H "Content-Type: application/json" \
--data '{
...
This is a curl representation of an API call to Airtable. In curl, -H specifies a
Header. For this API call, two headers are set. The first one is the
Authorization Header.
-H "Authorization: Bearer keytrcc12T45FGpoi"
AmbleMind.com
16
Hey! Darren here...
I know creating an app on your own can be a
handful. My company, AmbleMind, is here to help!
Before you spend a ton of time and energy on an
app you’re not sure will work, try AmbleMind. We
make it easier to create an app that’s tailor-made to
what you want to do.
We can help you work through your roadblocks or take the reins and build
version one of your app in one week. If you are ready to work with a strategic
partner, let’s get started!
Get Started
AmbleMind.com
17
Download