Build an API with Node.js and Express

Setting up Express and Node.jsNode.js Logo.svg

Make a directory

mkdir first-api

Run this command

npm init
  • Package name: first-api
  • Version: 1.0.0
  • Description: first-api
  • Entry point: app.js
  • Enter through the rest.

Add the Express package

yarn add express
yarn install

Create an app.js file your directory

Run this command to start your server

node app.js

Make some routes

Make a folder for the routes

mkdir routes

Make Models for Database Schema

Make a new directory called models

mkdir models

Create a new file for each resource

Creating a schema for Mongoose Create a directory called models/ in your server root.

// models/group.js

const mongoose = require('mongoose') const Schema = mongoose.Schema const group = new Schema({ id: UUID, name: { type: String, minLength: [3, 'Name not long enough'], required: [true, 'Name is required'], } groupId: Schema.Types.ObjectId, completed: Boolean, }) module.exports = group

Starting your server with app.js

// app.js
// import express const express = require('express'); // creates a new express application const app = express(); // define routes inline // method (path, handler) app.get('/', function(req, res) { // grab response and send it res.send('Hello world'); }); // listen (port, handler) app.listen(3000, function() { console.log('Blunderlist API listening on port 3000!'); });

Using MongoDB database using Mongoose

To install Mongoose for MongoDB use the following command. Mongoose is the tool we are using.

yarn add mongoose

http://mongoosejs.com/docs/queries.html

MongoDB Documentation

https://docs.mongodb.com/manual/tutorial/query-documents/

 

 

 

 

Visit sunny St. George, Utah, USA

Get In Touch

We would love to hear from you.

Please enter your email address.
Please enter a valid email address.
Please enter the verification number.
You have entered a wrong verification number.
Please enter a message.
Please check your message for any errors.
Your message has been sent successfully.
Sorry, error occured this time sending your message.
* required