3.4. API Routes

In this chapter, you’ll learn what API Routes are and how to create them.

What is an API Route?#

An API Route is a REST API endpoint. It exposes commerce features to external applications, such as storefronts, the admin dashboard, or third-party systems.

The Medusa core application provides a set of admin and store API routes out-of-the-box. You can also create custom API routes to expose your custom functionalities.


How to Create an API Route?#

An API Route is created in a TypeScript or JavaScript file under the src/api directory of your Medusa application. The file’s name must be route.ts or route.js.

Each file exports API Route handler functions for at least one HTTP method (GET, POST, DELETE, etc…).

For example, to create a GET API Route at /hello-world, create the file src/api/hello-world/route.ts with the following content:

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

Test API Route#

To test the API route above, start the Medusa application:

Then, send a GET request to the /hello-world API Route:

Code
curl http://localhost:9000/hello-world

When to Use API Routes#

Use API routes whenYou're exposing custom functionality to be used by a storefront, admin dashboard, or any external application.
Was this chapter helpful?
Edit this page