You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3.6 KiB

Create an API

Lesson Objectives

  1. Define API
  2. Initialize Directory
  3. Set Up Express Server
  4. Create Todo Controller
  5. Initialize Mongoose
  6. Create Todo Model
  7. Create Create Route
  8. Create Index Route
  9. Create Delete Route
  10. 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

Initialize Directory

  1. npm init
  2. set entry point as server.js
  3. touch server.js
  4. npm install express

Set Up Express Server

server.js:

const express = require('express');
const app = express();

app.listen(3000, ()=>{
    console.log('listening...');
});

Create Todo Controller

  1. mkdir controllers
  2. touch controllers/todos.js

controllers/todos.js:

const express = require('express');
const router = express.Router();

router.get('/', (req, res)=>{
    res.send('index');
});

module.exports = router;

server.js:

const todosController = require('./controllers/todos.js');
app.use('/todos', todosController);

Initialize Mongoose

  1. npm install mongoose

server.js:

const mongoose = require('mongoose');
//...farther down the page
mongoose.connect('mongodb://localhost:27017/meancrud', { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.once('open', ()=>{
    console.log('connected to mongod...');
});

Open terminal tabs for mongod and mongo

Create Todo Model

  1. mkdir models
  2. touch models/todos.js

models/todos.js:

const mongoose = require('mongoose');

const todoSchema = new mongoose.Schema({
    description: String,
    complete: Boolean
});

const Todos = mongoose.model('Todo', todoSchema);

module.exports = Todos;

Create Create Route

  1. We need to tell Express to expect JSON data in the body from AJAX, so we'll use express.json()
  2. 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:

app.use(express.json()); //use .json(), not .urlencoded()

controllers/todos.js

const Todos = require('../models/todos.js');
//...farther down the page
router.post('/', (req, res)=>{
    Todos.create(req.body, (err, createdTodo)=>{
        res.json(createdTodo); //.json() will send proper headers in response so client knows it's json coming back
    });
});

test: curl -X POST -H "Content-Type: application/json" -d '{"description":"weee","complete":true}' http://localhost:3000/todos

Create Index Route

controllers/todos.js:

router.get('/', (req, res)=>{
    Todos.find({}, (err, foundTodos)=>{
        res.json(foundTodos);
    });
});

test: curl http://localhost:3000/todos

Create Delete Route

router.delete('/:id', (req, res)=>{
    Todos.findByIdAndRemove(req.params.id, (err, deletedTodo)=>{
        res.json(deletedTodo);
    });
});

test: curl -X DELETE http://localhost:3000/todos/58f79d490708714536c02474

Create Update Route

controllers/todos.js:

router.put('/:id', (req, res)=>{
    Todos.findByIdAndUpdate(req.params.id, req.body, {new:true}, (err, updatedTodo)=>{
        res.json(updatedTodo);
    });
});

test: curl -X PUT -H "Content-Type: application/json" -d '{"description":"I updated this","complete":true}' http://localhost:3000/todos/58f7a4fd26b1a345e9281cb8