100% found this document useful (1 vote)
167 views

Understanding API: What Is An API?

The document discusses APIs and provides examples to help explain them. An API is an interface that allows software to interact with an existing application, accessing its data and functionality. It provides a set of functions and procedures that developers can use to build on top of an application. Popular web APIs like Google Maps, YouTube, and Twitter allow developers to integrate their functionality into other programs and websites. A base URL identifies the consistent part of a web address that an API call is made to.

Uploaded by

Yesmine Makkes
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
167 views

Understanding API: What Is An API?

The document discusses APIs and provides examples to help explain them. An API is an interface that allows software to interact with an existing application, accessing its data and functionality. It provides a set of functions and procedures that developers can use to build on top of an application. Popular web APIs like Google Maps, YouTube, and Twitter allow developers to integrate their functionality into other programs and websites. A base URL identifies the consistent part of a web address that an API call is made to.

Uploaded by

Yesmine Makkes
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 17

Understanding API

What Is an API?
The term “API” stands for Application Programming Interface. If you break that down word by
word, you can get a pretty good grasp of what it means.
An API is an interface that can be used to develop software that interacts with an existing
application.
In practice, an API is “a set of functions and procedures” that allow you to access and build upon
the data and functionality of an existing application.

Real world example


To describe the concept in further detail, we need to comprehend the basics. Let’s start with the
analogy of a restaurant menu. When we go to a restaurant to eat, we choose from the selection on
the menu. From this point, we convey our choices to the waiter. He/she then takes our choices to the
chef, they prepare our meal and it’s returned to us for a nice meal. From this point, we may ask
ourselves, do we know what the chef used in our fish or steak? How was it prepared? This back-
and-forth analogy serves as a starting point for this explanation.
Why? Because with an API, we really don’t know what’s going on behind the scenes at the
restaurant. All we really know is that we gave our food order, it was processed and out came our
dinner on a nice plate.
Let’s get back to development world, the API provides us with data that we do not necessarily know
how it has been created or served.
What API stands for ?Application Programming Interface
Google map API is a private API
False

Api works only with web applicationFalse

Introduction
A web service is a resource that’s made available over the internet. Therefore, web services, by
definition, require a network.
The term “web service” is defined by W3C (the World Wide Web Consortium) and so it technically
follows a whole host of standards.
To test web services, developers often use Postman.
To install Postman visit https://www.postman.com/
API of a web service
An API exactly defines the methods for one software program to interact with the other. When this
action involves sending data over a network, Web services come into the picture.
An API generally involves calling functions from within a software program
Web Service is A resource that’s made available over the internet
Web services can only work with reactFalse
All Web services are APIs but all APIs are not Web services.True

Requests
A web browser may be the client, and an application on a computer that hosts a web site may be the
server.
Example: A client (browser) submits a HTTP request to the server then the server returns a
response to the client.
The response contains status information about the request and may also contain the requested
content.

Methods
The most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET,
PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD)
operations, respectively. There are a number of other verbs, too, but are utilized less frequently. One
of those less-frequent methods, OPTIONS and HEAD are used more often than others.

POST
The post method is used to send data from the client (browser) to the server, as we can see in the
example below, we used the postman to hit the url 127.0.01 on the port 3000 with a post method the
body of this request contain the email and the password

GET
In this example, we use the get method to fetch data from the api

PUT
PUT is used for update requests to modify entries in the database. So generally PUT requests are
sent with an id as query or params and the new data in the body.
//id as query
http://localhost:3000/user/profile/?id=5e3bebed40dfda2656da1788
//id as params
http://localhost:3000/user/profile/5e3bebed40dfda2656da1788

PATCH

The HTTP PATCH request method applies partial modifications to a resource.


Unlike PUT method that only allows complete replacement of a document.

Delete

In this example, we sent a request to delete the user, the method delete is used with the id
5e3bebed40dfda2656da1788

Conclusion
HTTP defines a set of request methods to indicate the desired action to be performed for a given
resource. Although they can also be nouns, these request methods are sometimes referred to as
HTTP verbs, you could check https://www.w3schools.com/tags/ref_httpmethods.asp.
We use PUT and PATCH toUpdate a resource

Talking about Requests, a browser is a Client

The delete method need a query or a parameter (like id, or name ….)True

Response :Intro
HTTP Response is the packet of information sent by Server to the Client in response to an earlier
Request (Get, Post, Put ….) made by Client. HTTP Response contains the information requested by
the Client.

Status
HTTP response status codes indicate whether a specific HTTP request has been successfully
completed. Responses are grouped in five classes:
1. Informational responses (100–199),
2. Successful responses (200–299),
3. Redirects (300–399),
4. Client errors (400–499),
5. and Server errors (500–599).
What is the purpose of HTTP status codes?
HTTP status codes are standard response codes given by web site servers on the internet. The codes
help identify the cause of the problem when a web page or other resource does not load properly.

Status: example
HTTP response status description:
The Status-Code element in a server response, is a 3-digit integer where the first digit of the Status-
Code defines the class of response and the last two digits do not have any categorization role. There
are 5 values for the first digit. Here is a table describing the existing status value.
In the table below, we find the most used response status

Body
An HTTP message consists of a message header and an optional message body, separated by a
blank line, as illustrated above:

Body
Response Body contains the resource data that was requested by the client.
In the example below, City Hyderabad was requested for the weather data. If we take a look at the
response body, it contains the weather information of the City. It also has the information about the
Temperature, Humidity, Weather description and a few more weather properties of the city.
Response Body:

{
"City": "Hyderabad",
"Temperature": "25.7 Degree celsius",
"Humidity": "51 Percent",
"WeatherDescription": "haze",
"WindSpeed": "2.6 Km per hour",
"WindDirectionDegree": "120 Degree"
}

To summerize, an API specification needs to specify the responses for all API operations. Each
operation must have at least one response defined, usually a successful response. A response is
defined by its HTTP status code and the data returned in the response body and/or headers.
The http message consist to have a header and a body separated by a line False
A GET request sent to the server to retrieve a product. The request completed successfully but the
requested product does not exist in the database. The response status code should be :404
What is a Response Body ?Response Body contains the resource data that was requested by the
client

Intro
Since the beginning of this course, we were dealing with static data, sometimes hard coded, but in
real life applications we need to pull in data from an external resource.
What if you want to handle data from an API? That's the purpose of this section.
Specifically, we'll make use of the Fetch API and axios as examples for how to request and use data.

Example APIs
ProgrammableWeb, a site that tracks more than 15,500 APIs, lists Google Maps, Twitter, YouTube,
Flickr and Amazon Product Advertising as some of the the most popular APIs. The following list
contains several examples of popular APIs:
1. Google Maps API: Google Maps APIs lets developers embed Google Maps on webpages
using a JavaScript or Flash interface. The Google Maps API is designed to work on mobile
devices and desktop browsers. Link to api: Link
2. YouTube APIs: Google's APIs lets developers integrate YouTube videos and functionality
into websites or applications. It include the YouTube Analytics API, YouTube Data API,
YouTube Live Streaming API, YouTube Player APIs… link to youtube API: Link
3. Flickr API: The Flickr API is used by developers to access the Flick photo sharing
community data. The Flickr API consists of a set of callable methods, and some API
endpoints. Link to API: Link
4. Twitter APIs: Twitter offers two APIs.
• The REST API allows developers to access core Twitter data Link
• The Search API provides methods for developers to interact with Twitter Search and
trends data.Link to APIs: Link
5. Amazon Product Advertising API: Amazon's Product Advertising API gives developers
access to Amazon's product selection and discovery functionality to advertise Amazon
products to monetize a website. Link to API: Link

What is a base URL?


A base URL is, basically, the consistent part of your web address.
For example, you'll note that the address section https://www.google.com/ always appears in the
address bar.
This is the base URL. Everything that follows it is known as a URL path.
To find the base URL of your website, go to the site's front page. What you see in the address bar on
your site's front page is the base URL of your website.

The base URL example


The following is an example of a well-formed REST URL:
https://284-RPR-133.mktorest.com/rest/v1/lead/318581.json?
fields=email,firstName,lastName
Which is composed of the following parts:
Base URL: https://284-RPR-133.mktorest.com/rest
Path: /v1/lead/
Resource: 318582.json
Query parameter: fields=email,firstName,lastName
The twitter API helps developer to hack to twitter accountsFalse
What’s an url base
It’s the consistent part of a url
The query parameter is the parameter after
?
The Get with browser
Making an HTTP GET request is easy. Say you want to visit gomycode.co in your browser. All you
need to do is launch your browser and enter the address: https://www.gomycode.co

What’s fetch?
To fetch data using from an API, we can use the JavaScript fetch method. We can also use an
external library like axios, request, superagent, supertest and many other.
In this super skill, we are going to use the fetch method.
The fetch method is provided by the web Api and it’s supported by almost all the new browser
version.
PS. There is no need to install anything.
In this part we are going to get the list of courses from algolia API about redux.
"https://hn.algolia.com/api/v1/search?query=redux"

The Get with react


In this step we are going to create our react project, and in the App.js. What we are going to need is:
1. A state to set the returned values from the API
2. A state to handle the error (if there is any).
3. useEffect hook to hit the API after the component mount.
import React, { useEffect, useState } from "react";

const App = () => {


const [data, setData] = useState();// where to store the returned data
const [error, setError] = useState(null);// where to store the coming errors
useEffect(() => {
function fetchData() {// the function to fetch data from the api
fetch("https://hn.algolia.com/api/v1/search?query=redux")
.then(res => res.json())
.then(res => setData(res))
.catch(err => setError(err));
}

fetchData();
}, []);
return <div />;
};
export default App;

The Get with react


Well let’s explain some concepts, when we send a request to an API, it will take time to find the
needed data from its resources and return exactly the what we want, so JavaScript will not block the
rest of the operation, it will continue executing the rest of the program and when the API gives us
result of our request, JavaScript will handle it then. This is the asynchronous approach in
JavaScript, we will see it in more details in other super skill.
For now, to deal with asynchronous function JavaScript gives us the .then() .catch()
methods.
In a simpler words, when calling an api we tell the browser that the response will take some time so
go on continue your work and we will notify you when the response get back
function fetchData() {// the function to fetch data from the api
fetch("https://hn.algolia.com/api/v1/search?query=redux")
.then(res => res.json())// when the result comes back with success here
is what to do
.then(res => setData(res))
.catch(err => setError(err));// if there is an error here what you have
to do.
}

The Get with react


If we perform a console.log to the data state, we will receive the following result

It contain an array of object named hits, this is what we are going to show to user

The Get with react


If we perform a console.log to the data state, we will receive the following result
import React, { useEffect, useState } from "react";

const App = () => {


const [data, setData] = useState([]); // where to store the returned data
const [error, setError] = useState(null); // where to store the coming errors
useEffect(() => {
function fetchData() {
// the function to fetch data from the api
fetch("https://hn.algolia.com/api/v1/search?query=redux")
.then(res => res.json()) // when the result comes back with success here
is what to do
.then(res => setData(res.hits))
.catch(err => setError(err)); // if there is an error here what you have
to do.
}

fetchData();
}, []);

return (
<div>
<ul>
{data.map(course => (
<li>
<a href={course.url}> {course.title}</a>
</li>
))}
</ul>
</div>
);
};
export default App;

he Get with react: JSON


If we paste the URL of API in the browser, we will get a result like this one
This representation is called a JSON format that’s the result the API is sending to our application.

What’s JSON?
JSON (JavaScript Object Notation) is most widely used data format for data interchange on the
web. This data interchange can happen between two computers applications at different
geographical locations or running within same hardware machine.
The good thing is that JSON is a human and machine readable format. So while
applications/libraries can parse the JSON data – humans can also look at data and derive meaning
from it.
A JSON document may contains text, curly braces, square brackets, colons, commas, double quotes,
and maybe a few other characters.
Primarily, JSON is built on two structures:
1. A collection of name/value pairs. In various languages, this is realized as an object, record,
struct, dictionary, hash table, keyed list, or associative array.
2. An ordered list of values. In most languages, this is realized as an array, vector, list, or
sequence.
The fetch method can be used after installing the fetch API module
False

What is true about JSON ?JSON is a data format for data interchange on the webJSON is a human
and machine readable formatJSON is built in a structure of collection of name/value pairs.
The JSON document can contain methodsFalse

Post with React


The fetch API also gives us the ability to post data to the API.
function postData() {
// the function to post data to the api
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST", //setting the method
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},//setting the header
body: JSON.stringify(user)//setting the body
})
.then(res => res.json())
.then(res => setData(res))
.catch(err => setError(err));
}
In the example above we gonna add user in the Api
"https://jsonplaceholder.typicode.com/users", we gonna use Post Method

Post with React


In this code below we add an input for name, if we click add we will add a user inside the api
const App = () => {
const [user, setUser] = useState();
const handleSubmit = e => {
e.preventDefault();
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(user)
})
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err));
};

const handleChange = e =>


setUser({ id: Date.now(), [e.target.name]: e.target.value });
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Person Name:
<input type="text" name="name" onChange={handleChange} />
</label>
<button type="submit">Add</button>
</form>
</div>
);
};
export default App;

The first argument in post method is:


The path
The post request method, expect a second parameterTrue
The data sent in the request body should only be an objectFalse

What’s Axios?
Axios is a promise based HTTP client for the browser and Node.js.
By using Axios it’s easy to send asynchronous HTTP request to REST endpoints and perform
CRUD operations. The Axios library can be used in your plain JavaScript application or can be used
together with more advanced frameworks like React.js
There are some difference between axios the fetch web API:
Syntax: the http request using axios is more simple than using fetch
Support: the fetch web API is not supported by all the browser, on the other hand axios is supported
even by the old browser version (like IE)
Response timeout: the timeout set up is much easier using axois than using the fetch API.
Install Axios
To install axios we simply run the following command:
npm i axios
// or
npm install axios

Use Axios
Axios syntax is mostly like the fetch API.
To Perform a get request:
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})

Posting Data using Axios


The post request syntax is the following:
axios.post(url, data,config)
• Url: the url of the api
• Data: the data to be sent (optional field)
• Config: the header configuration (optional field)
axios
.post("/user", {
firstName: "Fred",
lastName: "Flintstone"
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});

Chaining request
Axios comes with build in feature which gives us the ability to send multiple requests.
const requestOne = axios.get("https://api.storyblok.com/v1/cdn/stories/health?
version=published&token=wANpEQEsMYGOwLxwXQ76Ggtt");
const requestTwo = axios.get(https://api.storyblok.com/v1/cdn/datasources/?
token=wANpEQEsMYGOwLxwXQ76Ggtt");
const requestThree = axios.get("https://api.storyblok.com/v1/cdn/stories/vue?
version=published&token=wANpEQEsMYGOwLxwXQ76Ggtt");
axios
.all([requestOne, requestTwo, requestThree])
.then(axios.spread((firstResponse, secondResponse, thirdResponse) => {
console.log(firstResponse.data,secondResponse.data, thirdResponse.data);
})
)
.catch(errors => {
console.error(errors);
});

Axios is promise base handlerTrue


Axios is built in module with Node.jsFalse
he third parameter in the post method is mandatory False

Headers:
HTTP header fields are components of the header section of request and response messages in the
HTTP Protocol. They define the operating parameters of an HTTP transaction.
//example of headers using postman

{
'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'PostmanRuntime/7.22.0',
accept: '*/*',
'cache-control': 'no-cache',
'postman-token': '35f27261-d4da-47d7-b540-9216d4fa694e',
host: '127.0.0.1:3001',
'accept-encoding': 'gzip, deflate, br',
'content-length': '37',
connection: 'keep-alive'
}

Headers:
The REST headers and parameters contain a wealth of information that can help you track down
issues when you encounter them. HTTP Headers are an important part of the API request and
response as they represent the meta-data associated with the API request and response. Headers
carry information for:
1. Request and Response Body
2. Request Authorization
3. Response Caching
4. Response Cookies
Other than the above categories HTTP headers also carry a lot of other information around HTTP
connection types, proxies etc. Most of these headers are for management of connections between
client, server and proxies and do not require explicit validation through testing.
Headers:
Headers are mostly classified as request headers and response headers, know the major request and
response headers. You will have to set the request headers when you are sending the request for
testing an API and you will have to set the assertion against the response headers to ensure that right
headers are being returned.
The headers that you will encounter the most during API testing are the following, you may need to
set values for these or set assertions against these headers to ensure that they convey the right
information and everything works fine in the API:
Authorization: Carries credentials containing the authentication information of the client for the
resource being requested.
WWW-Authenticate: This is sent by the server if it needs a form of authentication before it can
respond with the actual resource being requested. Often sent along with a response code of 401,
which means ‘unauthorized’.
Accept-Charset: This is a header which is set with the request and tells the server about which
character sets are acceptable by the client.
Content-Type: Indicates the media type (text/html or text/JSON) of the response sent to the client
by the server, this will help the client in processing the response body correctly.
Cache-Control: This is the cache policy defined by the server for this response, a cached response
can be stored by the client and re-used till the time defined by the Cache-Control header.

Headers:

The HTTP Header contains information about the HTTP Body and the Request/Response.
Information about the body is related to the content of the Body such as the length of the content
inside the body.
The information about Request/Response is the general information about the request/response and
it is not specific to the content of the body, example at what time the Request was made
The properties in header are specified as name-value pair which are separated from each other by a
colon ‘:’, (example name:value)

Headers:
Request Header: is present when you make a request to the server, it contains information about
the request such as the URL that you have requested, the method(GET, POST, HEAD) ,the browser
used to generate the request and other info.
Example
User-Agent:”Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101
Firefox/41.0″

The term browser is also called user-Agent. So even a simple request to a page involves sending the
information about your browser and the operating system you are using. You can see from the above
Header field that we are using Windows 10 and Firefox 41.0 browser.
Response Header: is sent from the server after the user sends a request for a particular page or
resource and it contains information such as the encoding used in the content, the server software
that is used on the server machine to generate the response and other information.

Most of the sites usually hide their server information in order to make it hard
for hackers to know which software is being used on the server.
The http header of a request contain information about the server
False
The authorization exists in the request body
False
Http header contain information about the body
True

You might also like