REST API

Samuel Kuttenkuler
5 min readFeb 4, 2020

(RE)presentational (S)tate (T)ransfer

What is REST?

  • REST is a resource-based software architectural style in which six constraints must be satisfied in order for an interface to be referred to as RESTful.
  • REST is resource based not action based ( nouns vs verbs).
  • SIX CONSTRAINTS: Uniform Interface, Stateless, Client — Server, Cacheable, Layered System, Code on Demand
Image result for rest api meme

In a RESTful API, we are thinking in nouns (resources) not in actions such as SOAP. Putting it simply, nouns and verbs or things and actions. These resources are identified by URI’s (a string that unambiguously identifies a particular resource). In REST you can have multiple URI’s referring to the same resource.

Representations are how we as developers manipulate our resources and is part of the resource state. BUT WAIT? I thought that one of the constraints of a RESTFUL API was being stateless?? So in this particular architecture style client and server are separate but the session state is held in the transfer between client and server NOT THE CLIENT. The server contains no client state. Each request that is made contains enough context to process the message given, though the messages must be very self descriptive. The format of the data in the representations are typically in Javascript Object Notation(JSON) or Extensible Markup Language(XML).

Representation Example:

Resource:

  • musician(Thelonious Monk)

Service:

  • Artist Info (GET)

Representation to get back:

  • Name, Albums, Age, etc
  • All in JSON or XML

THE SIX CONSTRAINTS OF REST

1. Uniform Interface

  • This defines the interface between the client and server by simplifying and decoupling the architecture. Uniform Interface is fundamental to a RESTful design. The relationship between client and server is established with HTTP verbs, URI’s, and HTTP responses:

— HTTP => GET, PUT, POST, DELETE

— URI’s => the resource name

— HTTP =>(status, body)

Image result for rest api cartoon

2. Stateless

  • The server contains none of the client state only session state is held.

3. Client / Server

  • When using REST one must assume a disconnected system, the client and server are not touching or connected, each are merely “shouting” at each other. Shouting a request, server listening for that request, taking that request, and shouting back a response that the client is listening for. The shouting and listening “connection” is Uniform Interface.

4. Cacheable

  • In the server, responses(representations) are cacheable. Caching is the ability to store copies of frequently accessed data in the client to server call and response interface. When a user sends a request with a resource representation, the request goes through a cache or multiple caches toward the server hosting the resource the user is listening for. If any of the caches along the request have a copy of the requested representation, it uses that copy to satisfy the request. This processes will reduce bandwidth, latency, and the overall load on servers.

5. Layered System

  • As mentioned in Client / Server, a developer must assume a disconnected system. In REST the software or hardware is the intermediary between client and server. Keeping this disconnected relationship is a great utility for scaling.

6. Code on Demand

  • The Code on Demand paradigm is the only constraint of the six that is optional. This constraint allows clients to improve flexibility by giving the server the control to decide how certain things will be done. The code(like Java applets or Javascript) lies inactive on a web server until a client requests a web page that holds a link to the code using the client’s web browser.

RESTful API calls with Node.js, Express, and MongoDB

install Express, Node, and MongoDB

  • server.js
//import packages
const express = require('express');
const mongojs = require('mongojs');
//connection to the db
const databaseURL = "vinyl";
const collections = ["records"];
const db = mongojs(databaseURL, collections);
//grant ability to create routes with express very easily
cost app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"));
/////////ROUTES/////////
////////////////////////
//listen for server
app.listen(3000, () => {
console.log("Server is listening on PORT: 3000");
});

In the ROUTES section in server.js will be examples of :

GET, PUT, POST, DELETE

  • GET
//If I (user) want to see the Records i have listened to //using get http verb when "newRecords" is visited.
app.get("/newRecords", (req, res) => {
// GET any resource in records collection with a variable listened // with a value of false.
db.records.find({ listened: true }, (error, data) => {
//if there is an error then log that error
if (error) {
console.log(error);} else {// server with send back the data the user is asking for in JSON
// format
res.json(data);
}});});
  • POST
// HTTP POST verb for when "add" is visited
app.post("/add", ({ newRecord }, res) => {
//new record Object that will add(POST) the new object to our db
const record = newRecord;
//set boolean for object
record.listened = false;
//mongojs save method to save to collection
db.records.save(record, (error, added) => {
if (error) {console.log(error);} else {// server responds with the updated collection including our new
// record
res.send(added);
}});});
  • PUT
//HTTP PUT verb for when "marklistened/:id" is visited
app.put("/marklistened/:id", ({ params }, res) => {
//mongo update method on records collection
db.records.update(
// match the id of the record we want updated
{ _id: mongojs.ObjectId(params.id) },
//once we find the record we want to update, set the new value
{ $set: { listened: true}
},(error, edited) => {if (error) {console.log(error);//if error send an error
res.send(error);
} else {
// server response to client call
res.send(edited);}});});
  • DELETE
HTTP DELETE verb for when "delete/:id" is visited
app.delete("/delete/:id", ({ params }, res) => {
//Mongojs method remove on the record we want deleted
db.records.remove(
// once we match the record ID we want to delete, remove it from the
// collection
{ _id: mongojs.ObjectId(params.id) },
(error, deleted) => {if (error) {console.log(error);res.send(error);} else {console.log(deleted);// server response to client call
res.send(deleted);
}});});

--

--