Check out the new web development bootcamp! learn more

It has already been one month since I first created this blog! I am trying to improve it. Do you have any ideas? leave a feedback

home > learn api

Web Dev Bootcamp ∙ Request Routing And Building an API

Hieu Nguyen · May 08, 2020 · 2 min read

webdevjavascriptcoursenodejsexpressjs

0

0 leave some love!

Goals

  • Learn how HTTP request works
  • Requesting routing with Express JS
  • Learn what an API is and how to build one

What is an HTTP Request

HTTP requests are just messages sent between an HTTP Client and a server.

The HTTP Client is typically a website or anything that is able to send a HTTP request

The HTTP server is a backend application that is able to receive a HTTP request, authorize the request, and then send some response back to the HTTP Client

How does HTTP Request Works

A HTTP request consists of 3 things:

1. The request line - this describes the request method and the request url

Request Methods:

  • GET - getting some data from a server
  • POST - posting or sending some data to a server
  • PUT - update some data in the server
  • DELETE - Delete some data in the server

The request url is the access point that the server exposes to the HTTP Client

2. Request Headers

request headers are additional information passed along with the HTTP request

Some examples of headers:

  • Accept-Charset
  • Accept-Encoding
  • Accept-Language
  • Authorization

3. Finally we have the request body or message

This is just the main content that we want to pass to the server from our HTTP client

Building an HTTP Server with Express

Let’s create our server first

  1. Create a new project folder
mkdir expressAPI
cd expressAPI
  1. Install Express and Create our server
npm init
npm install express
touch index.js

inside of the index.js file, add the following

var express = require("express")
var app = express()
const PORT = 3000
app.listen(PORT, () => {
  console.log(`listening on port ${PORT}`)
})
  1. Run the server
nodemon index.js

Creating Routes

Routes are like request url that you create to receive HTTP requests

Inside of the index.js file

app.get("/", (req, res, next) => {
  res.status(200).json("Hello from express server!")
})

This is telling our server that we are allow to receive a GET request to the root url and return a response with message : “Hello from express server!”

Testing our route

There are 2 ways to test your routes

  1. Using postman - an HTTP Client that allows you to send requests to your server

postman


Hieu Nguyen - Founder of devsurvival.com. I am also a video gamer, a full stack developer, and an anime lover. I'm also an advocate of teaching others how to code.
Archive