HTTP Methods

Express has a method for each HTTP verb: get, post, put, patch and delete.

Syntaxapp.post(path, handler)

HTTP requests carry a verb that describes intent. Express gives you one function per verb, and the same URL can behave differently for each.

MethodUsed for
app.get()Read data
app.post()Create data
app.put()Replace data
app.patch()Partially update data
app.delete()Remove data

Use app.all() to match every method on a path.

Example

Example · javascript
app.get('/users', (req, res) => res.send('List users'));
app.post('/users', (req, res) => res.send('Create a user'));
app.put('/users/:id', (req, res) => res.send('Replace a user'));
app.patch('/users/:id', (req, res) => res.send('Update a user'));
app.delete('/users/:id', (req, res) => res.send('Delete a user'));

When to use it

  • A REST API uses GET to fetch a user profile, POST to create a new one, PUT to replace it, and DELETE to remove it.
  • A form submission endpoint accepts POST /contact to receive data, while GET /contact serves the HTML form.
  • A PATCH endpoint on /api/settings allows clients to update only specific user preferences without replacing the entire resource.

More examples

GET and POST on same path

Shows GET (read list) and POST (create) on the same /users path — the HTTP method determines the action.

Example · js
app.get('/users', (req, res) => {
  res.json([{ id: 1, name: 'Alice' }]);
});

app.post('/users', (req, res) => {
  // req.body contains the new user data
  res.status(201).json({ created: true });
});

PUT and DELETE by ID

Defines PUT for full replacement and DELETE for removal, both scoped to a specific resource by :id.

Example · js
app.put('/users/:id', (req, res) => {
  const { id } = req.params;
  res.json({ updated: true, id });
});

app.delete('/users/:id', (req, res) => {
  res.status(204).send();
});

PATCH for partial update

Uses PATCH to accept a partial payload and merge only the provided fields into the stored resource.

Example · js
app.patch('/users/:id', (req, res) => {
  const { id } = req.params;
  const changes = req.body; // e.g. { email: '[email protected]' }
  // Apply changes to the stored user...
  res.json({ patched: true, id, changes });
});

Discussion

  • Be the first to comment on this lesson.
HTTP Methods — Express | SoundsCode