REST API from Scratch

REST API from Scratch

DIY REST API

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...
Recently visited Yahoo? See the little weather feature on the page? That's an API!image.png

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.
Its a mouthful...Lets break this

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

Dissecting further,

  • Endpoint: v2.jokeapi.dev/joke
  • Paths: Programming,Christmas
  • Parameters : type=twopart and blacklistFlags=nsfw

image.png

Reference: Joke API


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?
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...


But, what makes an API REST? image.png

RULES!

  • use HTTP request verbs image.png

Put vs. Patch:
The most awaited Amazon delivery of Teapot set arrived!
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

  • Follow specific patterns for routes and parameters


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

Guide:

  • Create New DB "wikidb"
  • Create New Collection "articles" with two fields Title and content and enter few document entries image.png

2. Setup Server

1) Initialize and Install packages

npm init

image.png

npm install mongoose body-parser ejs express

image.png

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

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

HOORAY! image.png

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

Post Success! image.png

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