HTTP Methods & app.route

GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS

HTTP Methods & app.route

Every HTTP method has a shorthand on the app instance; app.route also accepts an array of methods when a single handler should answer for several verbs.

4 min read Level 1/5 #fastify#routes#http
What you'll learn
  • Use the per-method shorthands
  • Pass an array to method in app.route
  • Pick the right verb for each operation

Fastify ships a shorthand for every HTTP method. They are all thin wrappers over app.route.

REST Convention

app.get('/posts', list);            // collection
app.get('/posts/:id', show);        // single resource
app.post('/posts', create);         // create
app.put('/posts/:id', replace);     // full replace
app.patch('/posts/:id', update);    // partial update
app.delete('/posts/:id', remove);   // delete

HEAD and OPTIONS exist too — app.head and app.options. Fastify also auto-generates a HEAD for every GET route unless you disable it.

Multiple Methods, One Handler

When the same logic answers both POST and PUT (think upsert), pass an array:

app.route({
  method: ['POST', 'PUT'],
  url: '/profile',
  handler: async (req) => upsertProfile(req.body),
});

Verb Cheatsheet

  • GET — fetch, never mutates, safe to cache
  • POST — create or non-idempotent action
  • PUT — replace the entire resource at the URL, idempotent
  • PATCH — partial update with a diff payload
  • DELETE — remove, idempotent
  • OPTIONS — used by browsers for CORS preflight; Fastify handles it automatically when @fastify/cors is registered

Pick the verb that matches the operation — clients, proxies, and OpenAPI tooling all rely on the convention.

Async Handlers →