# REST API from Scratch

# Application Programming Interface(API)
Its everywhere, everyone talks about it , we all use it even without realizing it...
So, lets gets more friendly with them...the APIs!

## What is API?
Cant talk about API without starting about the weather...
<br>
Recently visited Yahoo?
See the little weather feature on the page? That's an API!![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651449590967/lfNWwM7es.png align="left")


<strong>In simple words, API is a contract between the requestor and provider through agreed commands, functions ,protocols and objects to request interaction with an external system and obtain response in accordance to the agreement.
<br> Its a mouthful...Lets break this</strong>

## How do they work?

### Endpoint:
Lets imagine our provider is Mon Ami Gabi ,French bistro. The bistro is our endpoint.
Just because we are a customer, we do not have access to the entire place and remember just being at the bistro Endpoint doesn't satisfy our hunger.

### Paths:
Paths are authorized entry points within the bistro that we can use. Bar, Outdoor seating , indoor seating ,front desk and more. Kitchen and Inventory have restricted access.

### Parameters
Now, we are settled in a nice outdoor seating area and have our menu to place our order. Menu provides the options available to us and selection of specific items will provide us what we are looking for and that's our parameters/filters.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651459475478/kqaZvcpfO.png align="left")

Dissecting further,
- Endpoint: https://v2.jokeapi.dev/joke/
- Paths:      Programming,Christmas
- Parameters : type=twopart and blacklistFlags=nsfw

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651459546944/nh-zmI1Cj.png align="left")


*Reference: *[Joke API](https://sv443.net/jokeapi/v2/)
<hr />
# REpresentational State Transfer API
REST API is a architectural style and gold standards to design API.

What could have motivated Roy Fielding to vision REST API when he presented his research?
<br>
Probably, he was tired as I was walking around in Vegas strip
and thought how good it would have been if all these casinos are build with same architecture so the restaurants, the one-arm and the multi-arm bandits are exactly in the same floor and same direction in all these buildings..
We will not know...

<br>
But, what makes an API REST?
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651453029982/pXXTANg78.png align="left")


### RULES!
- use HTTP request verbs
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651456312111/cEKcrVnEm.png align="left")

Put vs. Patch:
<br>
The most awaited Amazon delivery of Teapot set arrived! <br>
The teacups are great. But the teapot is broken 😢.Of course, we want a replacement
- **Put **: If Amazon sends an entire Teapot set for replacement, that's a put
- **Patch**: If you get a replacement of just the broken teapot without the teacups, that's a patch!

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651455923526/lR5ORCllD.png align="left")

- Follow specific patterns for routes and parameters

<hr>
# How to create your own REST API?

## High Level Guide
1. Setup database
2. Setup Server
3. Get
4. Post
 

### 1. Setup database
*Reference: *[MongoDB, Hyper Setup](https://preethiv.hashnode.dev/getting-started-with-hyper-terminal-and-mongodb)

Guide:
- Create New DB "wikidb"
- Create New Collection "articles" with two fields Title and content and  enter few document entries
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651457550189/JfCSHEX1s.png align="left")

### 2. Setup Server
1) Initialize and Install packages

```
npm init
```

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651457904566/o3loPJJDc.png align="left")

```
npm install mongoose body-parser ejs express
```

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651458107026/kL7BfZj2n.png align="left")

2) Establish "App.js" and Require Packages and setup app

```
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));
``` 
3) Connect to MongoDB using Mongoose ;setup schema and model

```
//connect to Mongo DB using Mongoose
mongoose.connect("mongodb://localhost:27017/wikidb",{useNewUrlParser: true}); 
//create Article Schema
const articleSchema ={
  title: String,
  content: String
};

//create Article model
const Article = mongoose.model("Article",articleSchema);
``` 

### 3. GET

Setup the GET method to collect the documents from MongoDB article collections

```
//GET Route to fetch ALL Articles
app.get("/articles",function(req,res){
  Article.find(function(err,foundArticles){
    res.send(foundArticles);
    // console.log(foundArticles);
  });
});
``` 
Execute 

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651458604752/Wy_LVlzOl.png align="left")

Upon calling this route in the browser, we are able to get the documents entered in MongoDB using the API call

HOORAY!
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651458693066/W5l49xQus.png align="left")

*Reference* : Use Font Awesome extension in Chrome for JSON readability


### 4. POST
Use Postman to add a new document without the HTML forms


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651459061341/8NoBXMRM9.png align="left")

Post Success!
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651459031478/vOvxJ66MV.png align="left")


This instructions covers Get and Post to specific routes. This can be extended to Update(Put/Patch) and delete methods as well.

Hope you enjoyed the read!

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1651459219458/urUvpCVhk.png align="left")







