Structuring an API using Node.js and Express

 

Who am I?

Carolina Pascale Campos

Intern at Codeminer42

Student at UFSCar

https://github.com/CarolPC

 

 

Gotham API

A simple API using Node.js, express and mongo.  Its purpose is to illustrate how you can organize a RESTful application.

https://github.com/CarolPC/gotham-api

Request List Characters Flow

/characters

Request List Characters Flow

JSON Response

 

{
  "data": [
    {
      "_id": "581c8c0e8ae4dbf68e92e178",
      "name": "Batman",
      "ocupation": "CEO of Wayne Enterprises",
      "quote": "As a symbol I can be incorruptible. I can be everlasting.",
      "__v": 0,
      "firstAppearance": 1939
    },
    {
      "_id": "581cb70702eec407ff7414dd",
      "name": "Joker",
      "ocupation": "Villain",
      "quote": "Why so serious?",
      "__v": 0,
      "firstAppearance": 1940
    }
  ]
}

Mongoose Validation Errors

How to create custom errors with mongoose

charactersModel.js

const minFirstAppearance = [1939, 'The first appearance year should be greater than 1939'];

const charactersSchema = mongoSchema({
  firstAppearance: { type: Number, min: minFirstAppearance, default: 1939}
});

Mongoose Validation Errors

Request

{
    "name": "James Gordon",
    "ocupation": "Police Commissioner",
    "quote": "Because he's not our hero.",
    "firstAppearance": 1938
}

Mongoose Validation Errors

Response

{
  "error": {
    "type": "ValidationError",
    "message": "characters validation failed",
    "description": {
      "firstAppearance": "The first appearance year should be greater than 1939"
    }
  }
}

Thanks for your attention!

Any questions?

Structuring an API using Node.js and Express

By Carolina Pascale Campos

Structuring an API using Node.js and Express

  • 368
Loading comments...

More from Carolina Pascale Campos