# Full Stack Fundamental

### API

API stands for application programming interface, they are like a waiter which generate response as per our request. It is interface for interaction between two software. Those API which uses http or in simple handle internet based things are called as Web API's.API act as URL or endpoint for particular service. In some cases URL is normal means they don't have key( valid password or in technical terms an authenticator or token to use API ) neither they are paid they are called as **free API.**

First of all here is quick look how request and response model work:- if we want to open **amazon website** for purchasing something then we write URL of amazon website on **google** which **request** the **amazon server** for particular service further that server generate **response** in the form **HTML, CSS, JS** code which is rendered at last by our **browser** to show the amazon website.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723255707047/4791d2c7-321b-411f-96ce-7f305cf89670.png align="center")

but regarding the usage of API, we as user not access the amazon server directly instead we use their server API for own work and the response which is generated by the API is in form of raw data format called as JSON(Javascript object notation)

**Some random API example:-**

* [https://developer.x.com/en/docs/twitter-api](https://developer.x.com/en/docs/twitter-api):- we can make bot account on twitter using this API, we can reply or tag someone without creating account etc.
    
* [https://catfact.ninja/facts](https://catfact.ninja/facts):- facts regarding cat.( You can see particular format in which page is written that's is JSON )
    
* [https://developers.google.com/maps](https://developers.google.com/maps):- google map API.
    

### JSON

JSON stand for JavaScript object notation which is just a format of displaying data. JSON internally uses Javascript object where their keys are of type string. For more insight check this one [https://www.json.org/json-en.html](https://www.json.org/json-en.html). To check whether particular JSON is correct or not we use validator example [https://jsonlint.com/](https://jsonlint.com/)

Before JSON, API generate response in the form of XML. For more insight you can check out this one [https://www.imaginarycloud.com/blog/json-vs-xml](https://www.imaginarycloud.com/blog/json-vs-xml)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723257229481/ed1c08ad-3ddc-4f61-80dc-7da96c4889b1.png align="center")

**Accessing data from JSON**

Generally all the response generated by the API is in form of JSON which holds all data in the string type data. So we require to convert that data in our desired format using methods few of the them are:-

* **JSON.parse(data)** - to parse or convert JSON data into JS objects
    
* **JSON.stringify(json)** - to parse a JS object into JSON data.
    

### Testing API request

Generally we use the URL of particular API in the browser to test or we can say that usage of API. But this is not a efficient way to be used by developer to test their API, they use tools such as -[hoppscotch](https://hoppscotch.io/), [postman](https://www.postman.com/).

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723260593098/9d2935c2-b83a-4173-b8d6-cd1780612b67.png align="center")

text bar ro the right of GET text is where we write the API endpoint or URL , then we click send to generate the response which is shown below

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723260721838/f496c044-8151-46f5-a822-b37bb011c250.png align="center")

One thing to remember is that these tool are used at developer end for testing API they are not used at user end.

### Ajax

Ajax stands for asynchronous javascript and XML. It is process used by JSON to receive the request and generate response.

Earlier when we send request from our Javascript code to API, API further generate response in the form of XML. This whole process or request and response is asynchronous in nature. Hence it is called as Ajax.

### Http Verbs

Whenever we send request on http we use different verbs to perform functionality such as GET ( to receive data ), POST( to send data ), DELETE( to remove data).

## Status Codes

Different codes are used to show response generated by API some of them are:-

* 200:- OK
    
* 404:- Not Found
    
* 400:- Bad request
    
* 500:- Internal Server error.
    

[Status Code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)

### Adding Information in URLs

Adding additional information in the end point of an API.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723261986099/bdcb84c0-2220-43ed-ab84-8f872f2da9fb.png align="center")

?name=faraz&marks=100

You can play with this api [https://api.potterdb.com/v1](https://api.potterdb.com/v1) in the postman to get more clearity. We can add additional information in two ways one that is using Query string manually using key value pair or we can use different routes in form of variables.

When we send some key-value pair in API which not make sense then, then API ignore that key value pair.

**http headers**

headers are also used to send additional data to the API. They are in form of key-value pairs.

Try to open google browser and write some keyword to search to search and then visit the console and click on network tab on left side you can see many request and when we click on particular request we can see header information about particular request.

There are two types of headers :- request header and response header.

meta data also send with http headers.

[https://icanhazdadjoke.com/](https://icanhazdadjoke.com/)

### First Request

Before fetch() people uses XMLHTTPRequest() to send data however it has many drawbacks that they are not asynchronous in nature and we cannot use promises with them.

Now use use fetch() to send request, by default fetch() return promises in the form of response, we use promises method to work with API response.

```javascript
let url = "https://catfact.ninja/fact";
fetch(url).then((response) => {
  console.log(response);
}).catch((err) => {
  console.log("Error:- ", err);
})
```

Output:-

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723265690909/0e43600d-7b8a-41d4-af43-2bdb4fdd1830.png align="center")

to see data in readable format we use response.json() method.

Let's see how

```javascript
let url = "https://catfact.ninja/fact";
fetch(url).then((res) => {
  return res.json();
}).then((data) => {
  console.log("data 1 :- ", data.fact);
  return fetch(url);
}).then((res) => {
  return res.json();
}).then((data2) => {
  console.log("data 2:- ",data2.fact);
}).catch((err) => {
  console.log("Error:- ",err);
})
```

Output

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723265990222/e1c2c7be-715e-401f-971f-078b9a234f09.png align="center")

**using fetch with aysnc/await.**

```javascript
let url = "https://catfact.ninja/fact";
async function getFacts() {
  let res = fetch(url);
  console.log(res);
}
getFacts();
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723266546079/920d6ca3-e1c0-45e1-8b97-41710076017f.png align="center")

when we run this code promise can take time to generate response so it can be undefined but here process is so fast that we cannot se undefined and immediately promise state is change from undefined to fulfilled, to avoid the case we use await

```javascript
let url = "https://catfact.ninja/fact";
async function getFacts() {
  let res =  await fetch(url);
  console.log(res);
}
getFacts();
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723266618108/df8dad3d-288c-4373-9e98-522c62ab139e.png align="center")

again to read data in a desired format we use .json() method

```javascript
let url = "https://catfact.ninja/fact";
async function getFacts() {
  let res =  await fetch(url);
  let data = await res.json();
  console.log(data.fact);
}
getFacts();
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723266692975/ebb585e4-e193-47d5-bb6f-e4619aec6497.png align="center")

Sometime we can insert wrong url in the fetch()

```javascript
let url = "https://catfact.ninja/fact2";
async function getFacts() {
  let res =  await fetch(url);
  let data = await res.json();
  console.log(data.fact);
}
getFacts();
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723266806159/88e26161-e05b-467b-9e72-0a0a55129518.png align="center")

we use try-catch to deal with error.

```javascript
let url = "https://catfact.ninja/fact2";
async function getFacts() {
  try {
    let res =  await fetch(url);
    let data = await res.json();
    console.log(data.fact);
  } catch (err) {
    console.log("Error:- ",err);
  }
}
getFacts();
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723266895635/a53260eb-1571-44e1-9468-8f817c8fee46.png align="center")

Now to write multiple async call use promise chaining

```javascript
let url = "https://catfact.ninja/fact";
async function getFacts() {
  try {
    let res =  await fetch(url);
    let data = await res.json();
    console.log(data.fact);
    let res2 = await fetch(url);
    let data2 = await res2.json();
    console.log(data2.fact);
  } catch (err) {
    console.log("Error:- ",err);
  }
}
getFacts();
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723267087271/a74bc965-1f7b-4727-b2d9-000d0f002710.png align="center")

### Axios

Library to make http request in a better way. Axios also return promise. fetch() return data but it is not is readable format we have to parse it to json format, but in axios we get data in readable format directly parsing not required.

Note:- Do not use loop to call API's

[Installation](https://github.com/axios/axios?tab=readme-ov-file#installing)

```javascript
let url = "https://catfact.ninja/fact";
/* axios code  */
async function getFacts() {
  try {
    let res = await axios.get(url);
    console.log(res);
  } catch (err) {
    console.log("Error:- ", err);
  }
}
getFacts();
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723270214669/07536898-a293-4176-ac0e-4f86f37e2f57.png align="center")

%[https://codepen.io/farazalam2017/pen/NWZaNVq] 

%[https://codepen.io/farazalam2017/pen/VwJMjwV] 

**Axios with headers**

```javascript
const url = "https://icanhazdadjoke.com/";
async function getJokes() {
  try {
    let res = await axios.get(url);
    console.log(res.data);
  } catch (err) {
    console.log(err);
  }
}

getJokes();
```

Above code will be generating data in the html format as show below

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723289460266/e7e25451-2d3c-486b-8745-a9b00a421692.png align="center")

To get data in the json format we use headers together with response

```javascript
const url = "https://icanhazdadjoke.com/";
async function getJokes() {
  try {
    const config = { headers: { Accept: "application/json" } };
    let res = await axios.get(url, config);
    console.log(res.data);
  } catch (err) {
    console.log(err);
  }
}

getJokes();
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1723289582271/7589a125-f588-4609-9434-f7112ce0bb8c.png align="center")

**Updating Query String in axios**

%[https://codepen.io/farazalam2017/pen/VwJMKev] 

### Node js

It is a runtime environment, used for server side programming.

**node REPL**

REPL stands for read-evaluate-print-loop , used to write node code.

window object ~ global object in node js.

**Node files**

to run file with node we must have correct directory then to run write "node file\_name"

**Process**

this object provide information about and control over the current Node.js process

process.argv:- returns an array containing the command-line argument passed when the Node.js process was launched. When we want to pass additional information together with "node file\_name" command we use process.argv.

**module.exports**

require():- a built in function to include external modules that exists in separate file. They particularly search for index.js file as an entry point.

module.exports():- a special object, by default they send empty object( { } );

### NPM

npm is the standard package manager for Node.js file. It is like a library of package. Package is code written by someone to perform some functionality we can easily use them in our code through npm. It is command line tool to manage our packages. It comes preinstalled with node.

**node\_modules:-** folder which contain every installed dependency for your project.

**package-lock.json:-** it records the exact version of every installed dependency including its sub-dependencies and their version.

**package.json:-** it contains descriptive and functional metadata about a project. such as name, version, and dependencies.
