on GitHub" data-tooltip-id=":R1blcldtb:">v2.5.1·Edited Feb 14·
In this chapter, you’ll learn about path, query, and request body 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 /hello-world/:id
, where :id
is a path parameter, create the file src/api/hello-world/[id]/route.ts
with the following content:
The MedusaRequest
object has a params
property. params
holds the path parameters in key-value pairs.
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, to create an API route at /hello-world/:id/name/:name
, create the file src/api/hello-world/[id]/name/[name]/route.ts
with the following content:
You access the id
and name
path parameters using the req.params
property.
You can access all query parameters in the query
property of the MedusaRequest
object. query
is an object of key-value pairs, where the key is a query parameter's name, and the value is its value.
For example:
The value of req.query.name
is the value passed in ?name=John
, for example.
You can apply validation rules on received query parameters to ensure they match specified rules and types.
Learn more in this documentation.
The Medusa application parses the body of any request having a JSON, URL-encoded, or text request content types. The request body parameters are set in the MedusaRequest
's body
property.
For example:
1import type {2 MedusaRequest,3 MedusaResponse,4} from "@medusajs/framework/http"5 6type HelloWorldReq = {7 name: string8}9 10export const POST = async (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.
MedusaRequest
type accepts a type argument that indicates the type of the request body. This is useful for auto-completion and to avoid typing errors.To test it out, send the following request to your Medusa application:
This returns the following JSON object:
You can apply validation rules on received body parameters to ensure they match specified rules and types.
Learn more in this documentation.