newbreedofgeek
newbreedofgeek

Reputation: 3616

express.js API Endpoint Best Practice for CRUD

I'm building a REST API using express.js.

My API needs to provide all endpoints to do CRUD on "users", so I have the following so far:

app.get('/users', getAllUsers); // get all users
app.post('/users', createUser); // create a new user
app.put('/users', updateUser); // update a user
app.delete('/users', deleteUser); // delete a user

But whats a good practice endpoint to get a single user?

So ideally if you GET on /users/1234 I should only return User with ID 1234 but if I just do /users I should return all users as the ID was not detected.

How can I refactor my:

app.get('/users', getAllUsers);

to handle both cases?

Upvotes: 1

Views: 988

Answers (3)

Clarence Leung
Clarence Leung

Reputation: 2556

You can create a higher-level router, and then call app.use() / router.use() on it. This is the recommended approach in the Express documentation.

var express     = require('express');

var app         = express();
var usersRouter = express.Router();

usersRouter.get('/', function(req, res) {
    res.send('Got all users');
});

usersRouter.get('/:id', function(req, res) {
    res.send('Got user ' + req.params.id);
});

app.use('/users', usersRouter);

Upvotes: 7

code-jaff
code-jaff

Reputation: 9330

you can do so by providing id as an optional param and checking that in the controller function

for eg.

app.get('/users/:id?', getAllUsers);

But I'd prefer to go with single responsibility principle

app.get('/users', getAllUsers);
app.get('/users/:id', getUser);

Upvotes: 1

Remario
Remario

Reputation: 3863

You cant , the best practice is to isolate your route operations as much as possible. There to get a single id,such route must only get that data. Example.

var router = express.Router();
router.route('some/route/id/123').get(function(req,res){

console.log('id');
});
router.route('some/route/all').get(function(req,res){

console.log('all');
});

Upvotes: 1

Related Questions