Search code examples
parameterspathgetfastify

How to pass file or directory path as a REST API parameter to Fastify endpoint


Actually the question is in the header. A REST endpoint definition is below:

fastify.get('/dir/:path', async (request, reply) => {
  let res = await remote.getDir(request.params.path);
  return { res: res };
});

And a call is like

http://127.0.0.1:3000/dir//

The problem is that Fastify treats the path parameter as continuation of the URL, and says: "Route GET:/dir// not found"


Solution

  • The slash / is evaluated as a path segment as written in the standard

    To archive your goal you need to:

    1. define the path as a query parameter
    2. or define the path parameter but encode it in a format that doesn't use /, like the base64

    Example 1:

    const fastify = require('fastify')()
    
    fastify.get('/dir', {
      schema: {
        querystring: {
          type: 'object',
          required: ['path'],
          properties: {
            path: { type: 'string' }
          }
        }
      }
    },
    
    async function (request, reply) {
      return request.query
    })
    
    fastify.listen(8080)
    
    // call it with: http://localhost:8080/dir?path=/