4.1.2. API Route Parameters

In this chapter, you’ll learn about path, query, and request body parameters.

Path Parameters#

To create an API route that accepts a path parameter, create a directory within the route file's path whose name is of the format [param].

For example, to create an API Route at the path /message/{id}, where {id} is a path parameter, create the file src/api/store/hello-world/[id]/route.ts with the following content:

src/api/store/hello-world/[id]/route.ts
1import type {2  MedusaRequest,3  MedusaResponse,4} from "@medusajs/medusa"5
6export const GET = (7  req: MedusaRequest,8  res: MedusaResponse9) => {10  res.json({11    message: `[GET] Hello ${req.params.id}!`,12  })13}

The MedusaRequest object has a params property. params holds the path parameters in key-value pairs.

Multiple Path Parameters#

To create an API route that accepts multiple path parameters, create within the file's path multiple directories whose names are of the format [param].

For example, create an API route at src/api/store/hello-world/[id]/name/[name]/route.ts:

src/api/store/hello-world/[id]/name/[name]/route.ts
1import type {2  MedusaRequest,3  MedusaResponse,4} from "@medusajs/medusa"5
6export const GET = (7  req: MedusaRequest,8  res: MedusaResponse9) => {10  res.json({11    message: `[GET] Hello ${12      req.params.id13    } - ${req.params.name}!`,14  })15}

This API route expects two path parameters: id and name.


Query Parameters#

You can access all query parameters in the query property of the MedusaRequest object.

For example:

src/api/store/hello-world/route.ts
1import type {2  MedusaRequest,3  MedusaResponse,4} from "@medusajs/medusa"5
6export async function GET(7  req: MedusaRequest,8  res: MedusaResponse9): Promise<void> {10  res.json({11    message: `Hello ${req.query.name}`,12  })13}

Request Body Parameters#

The Medusa application parses the body of any request having its Content-Type header set to application/json. The request body parameters are set in the MedusaRequest's body property.

For example:

src/api/store/hello-world/route.ts
1import type {2  MedusaRequest,3  MedusaResponse,4} from "@medusajs/medusa"5
6type HelloWorldReq = {7  name: string8}9
10export const POST = (11  req: MedusaRequest<HelloWorldReq>,12  res: MedusaResponse13) => {14  res.json({15    message: `[POST] Hello ${req.body.name}!`,16  })17}

In this example, you use the name request body parameter to create the message in the returned response.

To test it out, send the following request to your Medusa application:

1curl -X POST 'http://localhost:9000/store/hello-world' \2-H 'Content-Type: application/json' \3--data-raw '{4  "name": "John"5}'

This returns the following JSON object:

1{2  "message": "[POST] Hello John!"3}
Was this chapter helpful?