|
1
|
import { Prerequisites } from "docs-ui" |
|
2
|
|
|
3
|
export const metadata = { |
|
4
|
title: `${pageNumber} Guide: Create Brand API Route`, |
|
5
|
} |
|
6
|
|
|
7
|
# {metadata.title} |
|
8
|
|
|
9
|
In the previous two chapters, you created a [Brand Module](../module/page.mdx) that added the concepts of brands to your application, then created a [workflow to create a brand](../workflow/page.mdx). In this chapter, you'll expose an API route that allows admin users to create a brand using the workflow from the previous chapter. |
|
10
|
|
|
11
|
An API Route is an endpoint that acts as an entry point for other clients to interact with your Medusa customizations, such as the admin dashboard, storefronts, or third-party systems. |
|
12
|
|
|
13
|
The Medusa core application provides a set of [admin](!api!/admin) and [store](!api!/store) API routes out-of-the-box. You can also create custom API routes to expose your custom functionalities. |
|
14
|
|
|
15
|
<Prerequisites |
|
16
|
items={[ |
|
17
|
{ |
|
18
|
text: "createBrandWorkflow", |
|
19
|
link: "/learn/customization/custom-features/workflow" |
|
20
|
} |
|
21
|
]} |
|
22
|
/> |
|
23
|
|
|
24
|
## 1. Create the API Route |
|
25
|
|
|
26
|
You create an API route in a `route.{ts,js}` file under a sub-directory of the `src/api` directory. The file exports API Route handler functions for at least one HTTP method (`GET`, `POST`, `DELETE`, etc…). |
|
27
|
|
|
28
|
<Note> |
|
29
|
|
|
30
|
Learn more about API routes [in this guide](../../../fundamentals/api-routes/page.mdx). |
|
31
|
|
|
32
|
</Note> |
|
33
|
|
|
34
|
The route's path is the path of `route.{ts,js}` relative to `src/api`. So, to create the API route at `/admin/brands`, create the file `src/api/admin/brands/route.ts` with the following content: |
|
35
|
|
|
36
|
 |
|
37
|
|
|
38
|
```ts title="src/api/admin/brands/route.ts" |
|
39
|
import { |
|
40
|
MedusaRequest, |
|
41
|
MedusaResponse, |
|
42
|
} from "@medusajs/framework/http" |
|
43
|
import { |
|
44
|
createBrandWorkflow, |
|
45
|
} from "../../../workflows/create-brand" |
|
46
|
|
|
47
|
type PostAdminCreateBrandType = { |
|
48
|
name: string |
|
49
|
} |
|
50
|
|
|
51
|
export const POST = async ( |
|
52
|
req: MedusaRequest<PostAdminCreateBrandType>, |
|
53
|
res: MedusaResponse |
|
54
|
) => { |
|
55
|
const { result } = await createBrandWorkflow(req.scope) |
|
56
|
.run({ |
|
57
|
input: req.validatedBody, |
|
58
|
}) |
|
59
|
|
|
60
|
res.json({ brand: result }) |
|
61
|
} |
|
62
|
``` |
|
63
|
|
|
64
|
You export a route handler function with its name (`POST`) being the HTTP method of the API route you're exposing. |
|
65
|
|
|
66
|
The function receives two parameters: a `MedusaRequest` object to access request details, and `MedusaResponse` object to return or manipulate the response. The `MedusaRequest` object's `scope` property is the [Medusa container](../../../fundamentals/medusa-container/page.mdx) that holds Framework tools and custom and core modules' services. |
|
67
|
|
|
68
|
<Note title="Tip"> |
|
69
|
|
|
70
|
`MedusaRequest` accepts the request body's type as a type argument. |
|
71
|
|
|
72
|
</Note> |
|
73
|
|
|
74
|
In the API route's handler, you execute the `createBrandWorkflow` by invoking it and passing the Medusa container `req.scope` as a parameter, then invoking its `run` method. You pass the workflow's input in the `input` property of the `run` method's parameter. You pass the request body's parameters using the `validatedBody` property of `MedusaRequest`. |
|
75
|
|
|
76
|
You return a JSON response with the created brand using the `res.json` method. |
|
77
|
|
|
78
|
--- |
|
79
|
|
|
80
|
## 2. Create Validation Schema |
|
81
|
|
|
82
|
The API route you created accepts the brand's name in the request body. So, you'll create a schema used to validate incoming request body parameters. |
|
83
|
|
|
84
|
Medusa uses [Zod](https://zod.dev/) to create validation schemas. These schemas are then used to validate incoming request bodies or query parameters. |
|
85
|
|
|
86
|
<Note> |
|
87
|
|
|
88
|
Learn more about API route validation in [this chapter](../../../fundamentals/api-routes/validation/page.mdx). |
|
89
|
|
|
90
|
</Note> |
|
91
|
|
|
92
|
You create a validation schema in a TypeScript or JavaScript file under a sub-directory of the `src/api` directory. So, create the file `src/api/admin/brands/validators.ts` with the following content: |
|
93
|
|
|
94
|
 |
|
95
|
|
|
96
|
```ts title="src/api/admin/brands/validators.ts" |
|
97
|
import { z } from "@medusajs/framework/zod" |
|
98
|
|
|
99
|
export const PostAdminCreateBrand = z.object({ |
|
100
|
name: z.string(), |
|
101
|
}) |
|
102
|
``` |
|
103
|
|
|
104
|
You export a validation schema that expects in the request body an object having a `name` property whose value is a string. |
|
105
|
|
|
106
|
You can then replace `PostAdminCreateBrandType` in `src/api/admin/brands/route.ts` with the following: |
|
107
|
|
|
108
|
```ts title="src/api/admin/brands/route.ts" |
|
109
|
// ... |
|
110
|
import { z } from "@medusajs/framework/zod" |
|
111
|
import { PostAdminCreateBrand } from "./validators" |
|
112
|
|
|
113
|
type PostAdminCreateBrandType = z.infer<typeof PostAdminCreateBrand> |
|
114
|
|
|
115
|
// ... |
|
116
|
``` |
|
117
|
|
|
118
|
--- |
|
119
|
|
|
120
|
## 3. Add Validation Middleware |
|
121
|
|
|
122
|
A middleware is a function executed before the route handler when a request is sent to an API Route. It's useful to guard API routes, parse custom request body types, and apply validation on an API route. |
|
123
|
|
|
124
|
<Note> |
|
125
|
|
|
126
|
Learn more about middlewares in [this chapter](../../../fundamentals/api-routes/middlewares/page.mdx). |
|
127
|
|
|
128
|
</Note> |
|
129
|
|
|
130
|
Medusa provides a `validateAndTransformBody` middleware that accepts a Zod validation schema and returns a response error if a request is sent with body parameters that don't satisfy the validation schema. |
|
131
|
|
|
132
|
Middlewares are defined in the special file `src/api/middlewares.ts`. So, to add the validation middleware on the API route you created in the previous step, create the file `src/api/middlewares.ts` with the following content: |
|
133
|
|
|
134
|
 |
|
135
|
|
|
136
|
```ts title="src/api/middlewares.ts" |
|
137
|
import { |
|
138
|
defineMiddlewares, |
|
139
|
validateAndTransformBody, |
|
140
|
} from "@medusajs/framework/http" |
|
141
|
import { PostAdminCreateBrand } from "./admin/brands/validators" |
|
142
|
|
|
143
|
export default defineMiddlewares({ |
|
144
|
routes: [ |
|
145
|
{ |
|
146
|
matcher: "/admin/brands", |
|
147
|
method: "POST", |
|
148
|
middlewares: [ |
|
149
|
validateAndTransformBody(PostAdminCreateBrand), |
|
150
|
], |
|
151
|
}, |
|
152
|
], |
|
153
|
}) |
|
154
|
``` |
|
155
|
|
|
156
|
You define the middlewares using the `defineMiddlewares` function and export its returned value. The function accepts an object having a `routes` property, which is an array of middleware objects. |
|
157
|
|
|
158
|
In the middleware object, you define three properties: |
|
159
|
|
|
160
|
- `matcher`: a string or regular expression indicating the API route path to apply the middleware on. You pass the create brand's route `/admin/brands`. |
|
161
|
- `method`: The HTTP method to restrict the middleware to, which is `POST`. |
|
162
|
- `middlewares`: An array of middlewares to apply on the route. You pass the `validateAndTransformBody` middleware, passing it the Zod schema you created earlier. |
|
163
|
|
|
164
|
The Medusa application will now validate the body parameters of `POST` requests sent to `/admin/brands` to ensure they match the Zod validation schema. If not, an error is returned in the response specifying the issues to fix in the request body. |
|
165
|
|
|
166
|
--- |
|
167
|
|
|
168
|
## Test API Route |
|
169
|
|
|
170
|
To test out the API route, start the Medusa application with the following command: |
|
171
|
|
|
172
|
```bash npm2yarn |
|
173
|
npm run dev |
|
174
|
``` |
|
175
|
|
|
176
|
Since the `/admin/brands` API route has a `/admin` prefix, it's only accessible by authenticated admin users. |
|
177
|
|
|
178
|
So, to retrieve an authenticated token of your admin user, send a `POST` request to the `/auth/user/emailpass` API Route: |
|
179
|
|
|
180
|
```bash |
|
181
|
curl -X POST 'http://localhost:9000/auth/user/emailpass' \ |
|
182
|
-H 'Content-Type: application/json' \ |
|
183
|
--data-raw '{ |
|
184
|
"email": "admin@medusa-test.com", |
|
185
|
"password": "supersecret" |
|
186
|
}' |
|
187
|
``` |
|
188
|
|
|
189
|
Make sure to replace the email and password with your admin user's credentials. |
|
190
|
|
|
191
|
<Note title="Tip"> |
|
192
|
|
|
193
|
Don't have an admin user? Refer to [this guide](../../../installation/page.mdx#create-medusa-admin-user). |
|
194
|
|
|
195
|
</Note> |
|
196
|
|
|
197
|
Then, send a `POST` request to `/admin/brands`, passing the token received from the previous request in the `Authorization` header: |
|
198
|
|
|
199
|
```bash |
|
200
|
curl -X POST 'http://localhost:9000/admin/brands' \ |
|
201
|
-H 'Content-Type: application/json' \ |
|
202
|
-H 'Authorization: Bearer {token}' \ |
|
203
|
--data '{ |
|
204
|
"name": "Acme" |
|
205
|
}' |
|
206
|
``` |
|
207
|
|
|
208
|
This returns the created brand in the response: |
|
209
|
|
|
210
|
```json title="Example Response" |
|
211
|
{ |
|
212
|
"brand": { |
|
213
|
"id": "01J7AX9ES4X113HKY6C681KDZJ", |
|
214
|
"name": "Acme", |
|
215
|
"created_at": "2024-09-09T08:09:34.244Z", |
|
216
|
"updated_at": "2024-09-09T08:09:34.244Z" |
|
217
|
} |
|
218
|
} |
|
219
|
``` |
|
220
|
|
|
221
|
### Troubleshooting |
|
222
|
|
|
223
|
#### Returned Empty Array |
|
224
|
|
|
225
|
If you sent a request to the API route and received an empty array in the response, make sure you've correctly created the middleware at `src/api/middlewares.ts` (with correct spelling). This is a common mistake that can lead to the middleware not being applied, resulting in unexpected behavior. |
|
226
|
|
|
227
|
--- |
|
228
|
|
|
229
|
## Summary |
|
230
|
|
|
231
|
By following the previous example chapters, you implemented a custom feature that allows admin users to create a brand. You did that by: |
|
232
|
|
|
233
|
1. Creating a module that defines and manages a `brand` table in the database. |
|
234
|
2. Creating a workflow that uses the module's service to create a brand record, and implements the compensation logic to delete that brand in case an error occurs. |
|
235
|
3. Creating an API route that allows admin users to create a brand. |
|
236
|
|
|
237
|
--- |
|
238
|
|
|
239
|
## Next Steps: Associate Brand with Product |
|
240
|
|
|
241
|
Now that you have brands in your Medusa application, you want to associate a brand with a product, which is defined in the [Product Module](!resources!/commerce-modules/product). |
|
242
|
|
|
243
|
In the next chapters, you'll learn how to build associations between data models defined in different modules. |