Raw
1 import { Details } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Pass Additional Data to Medusa's API Route`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn how to pass additional data in requests to Medusa's API Route.
10
11 ## Why Pass Additional Data?
12
13 Some of Medusa's API Routes accept an `additional_data` parameter whose type is an object. The API Route passes the `additional_data` to the workflow, which in turn passes it to its hooks.
14
15 This is useful when you have a link from your custom module to a Commerce Module, and you want to perform an additional action when a request is sent to an existing API route.
16
17 For example, the [Create Product API Route](!api!/admin/products/create-product) accepts an `additional_data` parameter. If you have a data model linked to it, you consume the `productsCreated` hook to create a record of the data model using the custom data and link it to the product.
18
19 ### API Routes Accepting Additional Data
20
21 <Details summaryContent="API Routes List">
22
23 - Campaigns
24 - [Create Campaign](!api!/admin/campaigns/create-campaign)
25 - [Update Campaign](!api!/admin/campaigns/update-a-campaign)
26 - Cart
27 - [Create Cart](!api!/store/carts/create-cart)
28 - [Update Cart](!api!/store/carts/update-a-cart)
29 - Collections
30 - [Create Collection](https://docs.medusajs.com/api/admin/collections/create-collection)
31 - [Update Collection](https://docs.medusajs.com/api/admin/collections/update-a-collection)
32 - Customers
33 - [Create Customer](!api!/admin/customers/create-customer)
34 - [Update Customer](!api!/admin/customers/update-a-customer)
35 - [Create Address](!api!/admin/customers/add-address)
36 - [Update Address](!api!/admin/customers/update-address)
37 - Draft Orders
38 - [Create Draft Order](!api!/admin/draft-orders/create-draft-order)
39 - Orders
40 - [Complete Orders](!api!/admin/orders/complete-order)
41 - [Cancel Order's Fulfillment](!api!/admin/orders/cancel-fulfillment)
42 - [Create Shipment](!api!/admin/orders/create-shipment)
43 - [Create Fulfillment](!api!/admin/orders/create-fulfillment)
44 - Products
45 - [Create Product](!api!/admin/products/create-product)
46 - [Update Product](!api!/admin/products/update-a-product)
47 - [Create Product Variant](!api!/admin/products/create-variant)
48 - [Update Product Variant](!api!/admin/products/update-variant)
49 - Product Tags
50 - [Create Product Tag](https://docs.medusajs.com/api/admin/product-tags/create-product-tag)
51 - [Update Product Tag](https://docs.medusajs.com/api/admin/product-tags/update-a-product-tag)
52 - Product Types
53 - [Create Product Type](https://docs.medusajs.com/api/admin/product-types/create-product-type)
54 - [Update Product Type](https://docs.medusajs.com/api/admin/product-types/update-a-product-type)
55 - Promotions
56 - [Create Promotion](!api!/admin/promotions/create-promotion)
57 - [Update Promotion](!api!/admin/promotions/update-a-promotion)
58
59 </Details>
60
61 ---
62
63 ## How to Pass Additional Data
64
65 ### 1. Specify Validation of Additional Data
66
67 Before passing custom data in the `additional_data` object parameter, you must specify validation rules for the allowed properties in the object.
68
69 To do that, use the middleware route object defined in `src/api/middlewares.ts`.
70
71 For example, create the file `src/api/middlewares.ts` with the following content:
72
73 <Note>
74
75 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
76
77 </Note>
78
79 ```ts title="src/api/middlewares.ts"
80 import { defineMiddlewares } from "@medusajs/framework/http"
81 import { z } from "@medusajs/framework/zod"
82
83 export default defineMiddlewares({
84 routes: [
85 {
86 method: "POST",
87 matcher: "/admin/products",
88 additionalDataValidator: {
89 brand: z.string().optional(),
90 },
91 },
92 ],
93 })
94 ```
95
96 The middleware route object accepts an optional parameter `additionalDataValidator` whose value is an object of key-value pairs. The keys indicate the name of accepted properties in the `additional_data` parameter, and the value is [Zod](https://zod.dev/) validation rules of the property.
97
98 In this example, you indicate that the `additional_data` parameter accepts a `brand` property whose value is an optional string.
99
100 <Note>
101
102 Refer to [Zod's documentation](https://zod.dev) for all available validation rules.
103
104 </Note>
105
106 ### 2. Pass the Additional Data in a Request
107
108 You can now pass a `brand` property in the `additional_data` parameter of a request to the Create Product API Route.
109
110 For example:
111
112 ```bash
113 curl -X POST 'http://localhost:9000/admin/products' \
114 -H 'Content-Type: application/json' \
115 -H 'Authorization: Bearer {token}' \
116 --data '{
117 "title": "Product 1",
118 "options": [
119 {
120 "title": "Default option",
121 "values": ["Default option value"]
122 }
123 ],
124 "shipping_profile_id": "{shipping_profile_id}",
125 "additional_data": {
126 "brand": "Acme"
127 }
128 }'
129 ```
130
131 <Note title="Tip">
132
133 Make sure to replace the `{token}` in the authorization header with an admin user's authentication token, and `{shipping_profile_id}` with an existing shipping profile's ID.
134
135 </Note>
136
137 In this request, you pass in the `additional_data` parameter a `brand` property and set its value to `Acme`.
138
139 The `additional_data` is then passed to hooks in the `createProductsWorkflow` used by the API route.
140
141 ---
142
143 ## Use Additional Data in a Hook
144
145 <Note>
146
147 Learn about workflow hooks in [this guide](../../../fundamentals/workflows/workflow-hooks/page.mdx).
148
149 </Note>
150
151 Step functions consuming the workflow hook can access the `additional_data` in the first parameter.
152
153 For example, consider you want to store the data passed in `additional_data` in the product's `metadata` property.
154
155 To do that, create the file `src/workflows/hooks/product-created.ts` with the following content:
156
157 ```ts title="src/workflows/hooks/product-created.ts"
158 import { StepResponse } from "@medusajs/framework/workflows-sdk"
159 import { createProductsWorkflow } from "@medusajs/medusa/core-flows"
160 import { Modules } from "@medusajs/framework/utils"
161
162 createProductsWorkflow.hooks.productsCreated(
163 async ({ products, additional_data }, { container }) => {
164 if (!additional_data?.brand) {
165 return
166 }
167
168 const productModuleService = container.resolve(
169 Modules.PRODUCT
170 )
171
172 await productModuleService.upsertProducts(
173 products.map((product) => ({
174 ...product,
175 metadata: {
176 ...product.metadata,
177 brand: additional_data.brand,
178 },
179 }))
180 )
181
182 return new StepResponse(products, {
183 products,
184 additional_data,
185 })
186 }
187 )
188 ```
189
190 This consumes the `productsCreated` hook, which runs after the products are created.
191
192 If `brand` is passed in `additional_data`, you resolve the Product Module's main service and use its `upsertProducts` method to update the products, adding the brand to the `metadata` property.
193
194 ### Compensation Function
195
196 Hooks also accept a compensation function as a second parameter to undo the actions made by the step function.
197
198 For example, pass the following second parameter to the `productsCreated` hook:
199
200 ```ts title="src/workflows/hooks/product-created.ts"
201 createProductsWorkflow.hooks.productsCreated(
202 async ({ products, additional_data }, { container }) => {
203 // ...
204 },
205 async ({ products, additional_data }, { container }) => {
206 if (!additional_data.brand) {
207 return
208 }
209
210 const productModuleService = container.resolve(
211 Modules.PRODUCT
212 )
213
214 await productModuleService.upsertProducts(
215 products
216 )
217 }
218 )
219 ```
220
221 This updates the products to their original state before adding the brand to their `metadata` property.