3.1.3. Create Brand API Route

Example ChapterThis chapter covers how to define an API route that creates a brand as the last step of the "Build Custom Features" chapter .

Create the file src/api/admin/brands/route.ts with the following content:

src/api/admin/brands/route.ts
8} from "../../../workflows/create-brand"9
10export const POST = async (11  req: MedusaRequest<CreateBrandInput>,12  res: MedusaResponse13) => {14  const { result } = await createBrandWorkflow(req.scope)15    .run({16      input: req.body,17    })18
19  res.json({ brand: result })20}

This adds a POST API route at /admin/brands. In the API route's handler, you execute the createBrandWorkflow, passing it the request body as input.

You return in the response the created brand.

NoteLearn more about API routes in this guide .

Test API Route#

To test it out, first, retrieve an authenticated token of your admin user by sending a POST request to the /auth/user/emailpass API Route:

Code
1curl -X POST 'http://localhost:9000/auth/user/emailpass' \2-H 'Content-Type: application/json' \3--data-raw '{4    "email": "admin@medusa-test.com",5    "password": "supersecret"6}'

Make sure to replace the email and password with your user's credentials.

Then, send a POST request to /admin/brands, passing the token received from the previous request in the Authorization header:

Code
1curl -X POST 'http://localhost:9000/admin/brands' \2-H 'Content-Type: application/json' \3-H 'Authorization: Bearer {token}' \4--data '{5    "name": "Acme"6}'

This returns the created brand in the response:

Example Response
1{2  "brand": {3    "id": "01J7AX9ES4X113HKY6C681KDZJ",4    "name": "Acme",5    "created_at": "2024-09-09T08:09:34.244Z",6    "updated_at": "2024-09-09T08:09:34.244Z"7  }8}

Summary#

By following the previous example chapters, you implemented a custom feature that allows admin users to create a brand by:

  1. Creating a module that defines and manages the Brand data model.
  2. Creating a workflow that uses the module's main service to create a brand record, and implements the compensation logic to delete that brand in case an error occurs.
  3. Creating an API route that allows admin users to create a brand.

Next Steps#

In the next chapters, you'll learn how to extend data models and associate the brand with a product.

Was this chapter helpful?
Edit this page