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 buildingWe 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 UpIn student examples for today:
cd holidays
mkdir holidays_api
cd holidays_api
touch server.js
npm init -y
- set entry point as server.js
npm install express
#
Set Up Express Serverserver.js:
const express = require("express");const app = express();const PORT = 3003;
app.listen(PORT, () => { console.log("๐๐", "celebrations happening on port", PORT, "๐๐");});
#
Create Holidays Controllermkdir controllers
touch 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 Mongoosenpm install mongoose
server.js:
const mongoose = require("mongoose");
//...farther down the page
// Error / Disconnectionmongoose.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 Modelmkdir models
touch 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:
// middlewareapp.use(express.json()); //use .json(), not .urlencoded()
controllers/holidays.js
const Holiday = require("../models/holidays.js");//...farther down the pageholidays.post("/", async (req, res) => { Holiday.create(req.body, (error, createdHoliday) => { if (error) { res.status(400).json({ error: error.message }); } // .json() will send proper headers in response so client knows it's json coming back res.status(200).send(createdHoliday); });});
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 Routecontrollers/holidays.js:
holidays.get("/", (req, res) => { Holiday.find({}, (err, foundHolidays) => { if (err) { res.status(400).json({ error: err.message }); } res.status(200).json(foundHolidays); });});
test: curl http://localhost:3003/holidays
#
Create Delete Routeholidays.delete("/:id", (req, res) => { Holiday.findByIdAndRemove(req.params.id, (err, deletedHoliday) => { if (err) { res.status(400).json({ error: err.message }); } res.status(200).json(deletedHoliday); });});
test: curl -X DELETE http://localhost:3003/holidays/5cc738d41f84cd0a2e1225bb
(replace the id with the id from your curl request)
#
Create Update Routecontrollers/holidays.js:
holidays.put("/:id", (req, res) => { Holiday.findByIdAndUpdate( req.params.id, req.body, { new: true }, (err, updatedHoliday) => { if (err) { res.status(400).json({ error: err.message }); } res.status(200).json(updatedHoliday); } );});
test: curl -X PUT -H "Content-Type: application/json" -d '{"name":"I updated this"}' http://localhost:3003/holidays/5cc738d41f84cd0a2e1225bb
#
server.js// Dependenciesconst express = require("express");const mongoose = require("mongoose");// Dependency configurationsconst app = express();const PORT = 3003;
// middlewareapp.use(express.json()); // use .json(), not .urlencoded()
// Database Error / Disconnectionmongoose.connection.on("error", (err) => console.log(err.message + " is Mongod not running?"));mongoose.connection.on("disconnected", () => console.log("mongo disconnected"));
// Database connectionmongoose.connect("mongodb://localhost:27017/merncrud", { useNewUrlParser: true,});mongoose.connection.once("open", () => { console.log("connected to mongoose...");});
// Controllers/Routesconst holidaysController = require("./controllers/holidays.js");app.use("/holidays", holidaysController);
// Listenapp.listen(PORT, () => { console.log("๐๐", "celebrations happening on port", PORT, "๐๐");});
#
models/holidays.jsconst 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.jsconst express = require("express");const holidays = express.Router();const Holiday = require("../models/holidays.js");
holidays.post("/", async (req, res) => { Holiday.create(req.body, (error, createdHoliday) => { if (error) { res.status(400).json({ error: error.message }); } res.status(200).send(createdHoliday); // .json() will send proper headers in response so client knows it's json coming back });});
holidays.get("/", (req, res) => { Holiday.find({}, (err, foundHolidays) => { if (err) { res.status(400).json({ error: err.message }); } res.status(200).json(foundHolidays); });});
holidays.delete("/:id", (req, res) => { Holiday.findByIdAndRemove(req.params.id, (err, deletedHoliday) => { if (err) { res.status(400).json({ error: err.message }); } res.status(200).json(deletedHoliday); });});
holidays.put("/:id", (req, res) => { Holiday.findByIdAndUpdate( req.params.id, req.body, { new: true }, (err, updatedHoliday) => { if (err) { res.status(400).json({ error: err.message }); } res.status(200).json(updatedHoliday); } );});
module.exports = holidays;