|
1
|
export const metadata = { |
|
2
|
title: `${pageNumber} API Routes`, |
|
3
|
} |
|
4
|
|
|
5
|
# {metadata.title} |
|
6
|
|
|
7
|
In this chapter, you’ll learn what API routes are and how to create them. |
|
8
|
|
|
9
|
## What is an API Route? |
|
10
|
|
|
11
|
An API route is a REST endpoint that exposes commerce features to external applications, such as storefronts, the admin dashboard, 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
|
--- |
|
16
|
|
|
17
|
## How to Create an API Route? |
|
18
|
|
|
19
|
You can create an API route 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`. |
|
20
|
|
|
21
|
 |
|
22
|
|
|
23
|
Each file exports API route handler functions for at least one HTTP method (`GET`, `POST`, `DELETE`, etc…). |
|
24
|
|
|
25
|
For example, to create a `GET` API route at `/hello-world`, create the file `src/api/hello-world/route.ts` with the following content: |
|
26
|
|
|
27
|
```ts title="src/api/hello-world/route.ts" |
|
28
|
import type { |
|
29
|
MedusaRequest, |
|
30
|
MedusaResponse, |
|
31
|
} from "@medusajs/framework/http" |
|
32
|
|
|
33
|
export const GET = ( |
|
34
|
req: MedusaRequest, |
|
35
|
res: MedusaResponse |
|
36
|
) => { |
|
37
|
res.json({ |
|
38
|
message: "[GET] Hello world!", |
|
39
|
}) |
|
40
|
} |
|
41
|
``` |
|
42
|
|
|
43
|
### Test the API Route |
|
44
|
|
|
45
|
To test the API route above, start the Medusa application: |
|
46
|
|
|
47
|
```bash npm2yarn |
|
48
|
npm run dev |
|
49
|
``` |
|
50
|
|
|
51
|
Then, send a `GET` request to the `/hello-world` API route: |
|
52
|
|
|
53
|
```bash |
|
54
|
curl http://localhost:9000/hello-world |
|
55
|
``` |
|
56
|
|
|
57
|
You should receive the following response: |
|
58
|
|
|
59
|
```json |
|
60
|
{ |
|
61
|
"message": "[GET] Hello world!" |
|
62
|
} |
|
63
|
``` |
|
64
|
|
|
65
|
--- |
|
66
|
|
|
67
|
## Next Chapters: Learn More About API Routes |
|
68
|
|
|
69
|
Follow the next chapters to learn about the different HTTP methods you can use in API routes, parameters and validation, protecting routes, and more. |