Skip to content

Instantly share code, notes, and snippets.

@shortcircuit3
Last active June 19, 2018 15:53
Show Gist options
  • Save shortcircuit3/978eeac988ebb4f772c25e8a884c8fa6 to your computer and use it in GitHub Desktop.
Save shortcircuit3/978eeac988ebb4f772c25e8a884c8fa6 to your computer and use it in GitHub Desktop.

For today's lesson, we're going to learn how to build a simple node js API!

API's are the backbone of building any app. It's how you can connect to a database, how you can accept payments, and how you can serve data to any application

A few prerequisites:

  • Basic knowledge of terminal commands
  • node installed
  • yarn or npm installed

Clone the starter repo

git clone git@github.com:milesalex/node-template.git api

Enter the folder and install the dependencies

cd app/
yarn install

Go to app.js and take a look at whats inside

import express from 'express'

const app = express()

app.get('/', (req, res) => {
  const response = { message: 'Hello from our api!' }
  res.json(response)
})

module.exports = app

Let's go through what's here. We import express, and then create an instance of our app by saving the express instance to a variable called app.

In express, it's very easy to create what's called "routes":

app.get('/', (req, res) => {
  const response = { message: 'Hello from our api!' }
  res.json(response)
})

When running an express server on your local computer, it will create a url. For example http://localhost:3000. The http://localhost part means "my local computer" and the 3000 means the port that the app is running on.

With the above code, this will create a webpage at the root url or '/'. Inside the code block, we store a json object as response and then we pass it to res.json().

The only thing thats important th know here is this is how you send JSON data to a website!

The final code in `app.js should look like this

import express from 'express'

const app = express()

app.get('/', (req, res) => {
  const response = { message: 'Hello from our api!' }
  res.json(response)
})

module.exports = app

Now, go back to the terminal and run

yarn run dev

And then you should see

DONE  Compiled successfully in 30ms

Example app listening on port http://localhost:5678!

Go to http://localhost:5678 and you should see a json response like this!!!

{
  "message": "Hello from our api!"
}

Yayy!! You just built an API! This is a core build block of building apps. Play around, see what you can do!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment