Reputation: 97
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 e.t.c
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.
Upvotes: 2
Views: 61
Reputation: 2353
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.
Upvotes: 1