REST

Creating a REST API Service using Node and Express

Swagger Logo by Fehguy is licensed under CC

Swagger Logo by Fehguy is licensed under CC

HTTP Methods/Verbs

Hypertext Transfer Protocol (HTTP) defines a set of request methods that a client application will use to ask an HTTP server to do something. HTTP request methods are often called verbs. HTTP verbs include:

  • Get A client application will use a Get method to retrieve something from an HTTP server. 
  • Post A client application will use a Post method to send something to an HTTP server.
  • Put A client application will use a Put method to request that something managed by an HTTP server is updated.
  • Delete A client application will use the Delete method to request that something managed by an HTTP server is thrown away.

API Routes

Routing determines how an HTTP server will respond to a client request. The client application will specify a path and an HTTP verb.

Route parameters are passed as part of the URL provided to the HTTP server.

Example GET requests:

https://localhost/books
request details of all books

https://localhost/books/1788395549
request details of the book with ISBN Number 1788395549 

Route handlers and Response methods

Route handlers are functions that execute on the HTTP server when a request is received from the client application.

Response methods are used to send something back to the client application. Response methods include:

  • send() Sends a response to the client.

  • sendFile() Sends a file to the client.

  • redirect() Redirects the request.

  • json() Sends a JavaScript object to the client.

  • status() Sets the HTTP status code
Example route handlers

Using Node.js and Express

npm can be used to initialise a REST API project.

Use these commands:

$ mkdir books
$ cd books
$ npm init
$ npm i express

The package.json file

The package.json file generated by npm should be updated to:

package.json

The index.js file

The index.js file generated by npm should be updated to:

index.js

The Dockerfile

Visual Studio Code is able to add a Dockerfile to a Node.js project automagically.

Open the Command Palette (⇧⌘P) and use the "Docker: Add Docker Files to Workspace..." command:

Dockerfile

FROM node:12.18-alpine
ENV NODE_ENV=production
WORKDIR /usr/src/app
COPY ["package.json", "package-lock.json*", "npm-shrinkwrap.json*", "./"]
RUN npm install --production --silent && mv node_modules ../
COPY . .
EXPOSE 5000
CMD ["npm", "start"]

REST API Service

/books route

/books/id route with a valid id

/books/id with an invalid id