简体   繁体   中英

How to properly handle my routing for a REST API

Apologies if this is a newbie question . How should I go about structuring my REST API (I use Node & Express).

const mongoose = require('mongoose');

const recipeSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {
        type: String,
        required: true
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'UserData',
        required: true
    },
    description: String,
    ingredients: [String],
    steps: [String],
    bookmarkNumber: Number,
    likeNumber: Number,
    rating: Number
})

module.exports = mongoose.model('Recipe', recipeSchema); 

While I understand I can use the following for larger scale functions like creating recipes and deleting recipes and etc

router.get('/', (req, res, next) => {
  // Get Recipes
});

router.post('/',checkAuth, (req, res, next) => {
  // Create Recipe
});

router.get('/:recipeID', (req, res, next) => {
// Get Specific Recipe
});

However I am currently stuck on how to handle the inner details or specific resources. For example : Let's say I would like to add a step to the recipe. Would this specific instance be one where I can put a verb or ? My current idea is to:

router.post('/:recipeID/steps',checkAuth, (req, res, next) => {
  // Add Steps to recipeID if it exists
});

so to basically add urls for the properties and handle them that way since verbs are apparently a REST API sin.

router.post('/:recipeID/:steps',checkAuth, (req, res, next) => {
   if (req.params.steps === 'first') {//based on your requirements

     } else if (condition) {

     }
});

However, There are a few rest API rules for different actions.

  • GET /users : to get user list.
  • GET /users/:userid : to get information to specific user.
  • POST /users : to create user.
  • PUT /users to update specific user information.

It might help you to understand the best approach of design API endpoints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM