No description, website, or topics provided.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
README.md

README.md

GA Cog

Reviewing RESTful JSON API's

Objectives

  1. Review JSON API's as a concept
  2. Review JSON API's as implemented in Express JS

JSON API's should be RESTful.

REST is well agreed upon as the best practice for the architecture of backend applications.

Remember:

GET ALL VIDEOS "/videos"

GET VIDEO BY ID "/vidoes/:id"

GET ALL COMEDIANS "/comedians"

GET COMEDIAN: "/comedians/:id"

GET ALL VIDEOS BY COMEDIAN "/comedians/:id/videos"

GET VIDEO BY COMEDIAN "/comedians/:id/videos/:id"

What is a JSON API?

Last unit we focused on building Full Stack Express Applications using EJS. But before we got there, we spent a little time serving up JSON before we learned templating.

In simple terms, that's what a JSON API is. It is a backend application with no views, it just accepts and serves JSON. In some cases, it simply serves as a interface for a database, and only implements simple CRUD actions.

Example Controller for Basic CRUD JSON API

const index = (req, res) => {
    Motorcycle.find(function(err, motorcycles) {
      res.json(motorcycles);
    });
}

const show = (req, res) => {
  Motorcycle.findOne({id: req.params.id}, function(err, motorcycle) {
      res.json(motorcycle);
  });
}

const create = (req, res) => {
    Motorcycle.create(req.body, (err, motorcycle) => {
        if (err) {
            return res.status(500).send(err);
        } else {
        	res.json(motorcycle);
   		}
	});
};

const update = (req, res) => {
  Motorcycle.findByIdAndUpdate(req.params.id, req.body (err, motorcycle) => {
    if(err || !motorcycle) {
      return res.status(500).send(err);
    } else {
      res.json(motorcycle);
    }
}

const destroy = (req, res) => {
  Motorcycle.findByIdAndRemove(req.params.id, (err, motorcycle) => {
    if (err) {
        return res.status(500).send(err);
    }
    let response = {
        message: "Motorcycle successfully deleted",
        id: motorcycle._id
    };
    return res.status(200).send(response);
}

In other cases, JSON API's can have a lot of business logic:

Example with business logic:

const show = (req, res) => {
  let bikeId = req.params.id;
  Motorcycle.findOne({id: bikeId}, function(err, motorcycle) {
      motorcycle.usersWithSameBikeNearUser = getDealersByZipcode(bikeId, res.locals.currentUser.zipcode);
      motorcycle.maintenanceSchedule       = getMaintenanceSchedule(bikeId);
      res.json(motorcycle);
  });
}

const getDealersByZipcode = (bikeId, zipcode) {
    console.log("not yet implemented")
    return [];
}

JSON API best practices Review

  1. scope your api in an 'api' namespace.
  2. version your api
https://www.comedyvideos.com/api/v2/comedians/2/videos

Decoupled Applications

A decoupled application is where the front end treats its own back end like an external API, rather than the backend serving up the front end application.

Many of you made use of JSON for your full stack Express app by using AJAX. That's awesome! You could do the same thing with a React front end. Essentiall, you just serve up that initial index.html page that contains that <div id="root"></div> from within your Express App, and put all of your React files in the Public folder.

This can be great, but decoupled apps have some advantages.

  1. If you ever want to change back end technologies, like move from Express to Django, or vice versa, the ONLY thing you need to change on your front end are the API endpoints in your AJAX calls.

  2. If you ever want to change front end technologies, like go from React to Vue, or vice versa, you litterally don't need to touch your back end at all.

  3. You have two smaller repos with less code. Have a React dev that knows nothing about Express? Great! They don't have to. Have an Express dev who knows nothing about React? Great! They don't have to. They work on completely seperate code bases!

Drawbacks:

There's only one: you have to set up CORS, or cross origin resource sharing. But don't worry, that's easy!

CORS in Express

npm install cors

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())

It's as simple as that to get started. This will allow requests to any route from ANY origin, so in the future, you will want to configure CORS to ONLY take requests from your front end app, unless you want it open to the public.

Check out the node modules github for details on how to configure CORS more.