Create an API
Lesson Objectives
- Define API
- Set Up Express Server
- Create Holiday Controller
- Initialize Mongoose
- Create Holiday Model
- Create Create Route
- Create Index Route
- Create Delete Route
- Create Update Route
Define API
- An API stands for Application Program Interface
- It is a set of routines, protocols, and tools for building software applications
- It specifies how software components should interact
- Essentially it's documentation, but in the industry, it's come to mean a program or some existing software that you use to build your own app
- In unit 1 we used a 3rd Party API, now we'll make our own and have React consume it
What we're building
We live in a time where there are so many holidays! Many times we forget to celebrate. So we'll build a holidays app to create, show and delete our holidays, we'll also be able to update whether or not we've celebrated the holiday
We're going to have a top level folder that will hold both of our apps

First we'll build our API which will just serve JSON. We'll create, update, and delete using cURL

Once we have built and tested our back end we'll build our React front end using Create-React App
Class build:

For lab, you'll continue on your own to click the balloons in order to increase likes and press the pencil to show a pre-filled form to let you edit the whole field:

Set Up
In student examples for today:
cd holidaysmkdir holidays_apicd holidays_apitouch server.jsnpm init -y- set entry point as server.js
npm install express
Set Up Express Server
server.js:
const express = require("express");
const app = express();
const PORT = 3003;
app.listen(PORT, () => {
console.log("🎉🎊", "celebrations happening on port", PORT, "🎉🎊");
});
Create Holidays Controller
mkdir controllerstouch controllers/holidays.js
controllers/holidays.js:
const express = require("express");
const app = express();
const PORT = 3003;
app.listen(PORT, () => {
console.log("🎉🎊", "celebrations happening on port", PORT, "🎉🎊");
});
server.js:
const holidaysController = require("./controllers/holidays.js");
app.use("/holidays", holidaysController);
visit : http://localhost:3003/holidays
Initialize Mongoose
npm install mongoose
server.js:
const mongoose = require("mongoose");
//...farther down the page
// Error / Disconnection
mongoose.connection.on("error", (err) =>
console.log(err.message + " is Mongod not running?")
);
mongoose.connection.on("disconnected", () => console.log("mongo disconnected"));
//...farther down the page
mongoose.connect("mongodb://localhost:27017/holidays", {
useNewUrlParser: true,
});
mongoose.connection.once("open", () => {
console.log("connected to mongoose...");
});
Open terminal tabs for mongod and mongo
Create Holiday Model
mkdir modelstouch models/holidays.js
Our holidays should:
- have a required name
- a boolean of whether or not we celebrated this holiday this year
- a description, let's default it to
best holiday ever! - likes, a number, default it to 0
- tags, an array of strings
models/holidays.js:
const mongoose = require("mongoose");
const holidaySchema = mongoose.Schema({
name: { type: String, required: true },
celebrated: { type: Boolean, default: false },
description: { type: String, default: "Best holiday ever!" },
likes: { type: Number, default: 0 },
tags: [{ type: String }],
});
module.exports = mongoose.model("Holiday", holidaySchema);
Create Create Route
- We need to tell Express to expect JSON data in the body from AJAX, so we'll use
express.json() - We'll also need to tell the client that the data coming back is JSON, not HTML, so we'll do
res.json()
server.js:
// middleware
app.use(express.json()); //use .json(), not .urlencoded()
controllers/holidays.js
const Holiday = require("../models/holidays.js");
//...farther down the page
holidays.post("/", async (req, res) => {
try {
const createdHoliday = await Holiday.create(req.body);
res.status(200).send(createdHoliday);
} catch (error) {
res.status(400).json({ error: error.message });
};
});
Let's make a handful of holidays:
test: curl -X POST -H "Content-Type: application/json" -d '{"name":"World Kindness"}' http://localhost:3003/holidays
test: curl -X POST -H "Content-Type: application/json" -d '{"name":"Spicy Hermit Cookie"}' http://localhost:3003/holidays
test: curl -X POST -H "Content-Type: application/json" -d '{"name":"Lost Sock Memorial"}' http://localhost:3003/holidays
test: curl -X POST -H "Content-Type: application/json" -d '{"name":"Bathtub Party"}' http://localhost:3003/holidays
test: curl -X POST -H "Content-Type: application/json" -d '{"name":"Zipper"}' http://localhost:3003/holidays
test: curl -X POST -H "Content-Type: application/json" -d '{"name":"Test Delete Route"}' http://localhost:3003/holidays
Create Index Route
controllers/holidays.js:
holidays.get("/", async (req, res) => {
try {
const foundHolidays = await Holiday.find({});
res.status(200).send(foundHolidays);
} catch (error) {
res.status(400).json({ error: error.message });
};
});
test: curl http://localhost:3003/holidays
Create Delete Route
holidays.delete("/:id", async (req, res) => {
try {
const deletedHoliday = await Holiday.findByIdAndRemove(req.params.id);
res.status(200).send(deletedHoliday);
} catch (error) {
res.status(400).json({ error: error.message });
};
});
test: curl -X DELETE http://localhost:3003/holidays/5cc738d41f84cd0a2e1225bb (replace the id with the id from your curl request)
Create Update Route
controllers/holidays.js:
holidays.put("/:id", async (req, res) => {
try {
const updatedHoliday = await Holiday.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true });
res.status(200).send(updatedHoliday);
} catch (error) {
res.status(400).json({ error: error.message });
};
});
test: curl -X PUT -H "Content-Type: application/json" -d '{"name":"I updated this"}' http://localhost:3003/holidays/5cc738d41f84cd0a2e1225bb
server.js
// Dependencies
const express = require("express");
const mongoose = require("mongoose");
// Dependency configurations
const app = express();
const PORT = 3003;
// middleware
app.use(express.json()); // use .json(), not .urlencoded()
// Database Error / Disconnection
mongoose.connection.on("error", (err) =>
console.log(err.message + " is Mongod not running?")
);
mongoose.connection.on("disconnected", () => console.log("mongo disconnected"));
// Database connection
mongoose.connect("mongodb://localhost:27017/merncrud", {
useNewUrlParser: true,
});
mongoose.connection.once("open", () => {
console.log("connected to mongoose...");
});
// Controllers/Routes
const holidaysController = require("./controllers/holidays.js");
app.use("/holidays", holidaysController);
// Listen
app.listen(PORT, () => {
console.log("🎉🎊", "celebrations happening on port", PORT, "🎉🎊");
});
models/holidays.js
const mongoose = require("mongoose");
const holidaySchema = mongoose.Schema({
name: { type: String, required: true },
celebrated: { type: Boolean, default: false },
description: { type: String, default: "Best holiday ever!" },
likes: { type: Number, default: 0 },
tags: [{ type: String }],
});
module.exports = mongoose.model("Holiday", holidaySchema);
controllers/holidays.js
const express = require("express");
const holidays = express.Router();
const Holiday = require("../models/holidays.js");
holidays.post("/", async (req, res) => {
try {
const createdHoliday = await Holiday.create(req.body);
res.status(200).send(createdHoliday); // .json() will send proper headers in response so client knows it's json coming back
} catch (error) {
res.status(400).json({ error: error.message });
};
});
holidays.get("/", async (req, res) => {
try {
const foundHolidays = await Holiday.create({});
res.status(200).send(foundHolidays);
} catch (error) {
res.status(400).json({ error: error.message });
};
});
holidays.delete("/:id", async (req, res) => {
try {
const deletedHoliday = await Holiday.findByIdAndRemove(req.params.id);
res.status(200).send(deletedHoliday);
} catch (error) {
res.status(400).json({ error: error.message });
};
});
holidays.put("/:id", async (req, res) => {
try {
const updatedHoliday = await Holiday.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true });
res.status(200).send(updatedHoliday);
} catch (error) {
res.status(400).json({ error: error.message });
};
});
module.exports = holidays;