docs: update endpoints to use file-routing approach (#5397)
- Move the original guides for creating endpoints and middlewares to sub-sections in the Endpoints category. - Replace existing guides for endpoints and middlewares with the new approach. - Update all endpoints-related snippets across docs to use this new approach.
This commit is contained in:
@@ -21,11 +21,11 @@ export interface AdminPostProductsProductReq {
|
||||
*/
|
||||
discountable?: boolean
|
||||
/**
|
||||
* An array of images of the Product. Each value in the array is a URL to the image. You can use the upload endpoints to upload the image and obtain a URL.
|
||||
* An array of images of the Product. Each value in the array is a URL to the image. You can use the upload API Routes to upload the image and obtain a URL.
|
||||
*/
|
||||
images?: Array<string>
|
||||
/**
|
||||
* The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload endpoints to upload the thumbnail and obtain a URL.
|
||||
* The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload API Routes to upload the thumbnail and obtain a URL.
|
||||
*/
|
||||
thumbnail?: string
|
||||
/**
|
||||
|
||||
@@ -25,11 +25,11 @@ export interface AdminPostProductsReq {
|
||||
*/
|
||||
discountable?: boolean
|
||||
/**
|
||||
* An array of images of the Product. Each value in the array is a URL to the image. You can use the upload endpoints to upload the image and obtain a URL.
|
||||
* An array of images of the Product. Each value in the array is a URL to the image. You can use the upload API Routes to upload the image and obtain a URL.
|
||||
*/
|
||||
images?: Array<string>
|
||||
/**
|
||||
* The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload endpoints to upload the thumbnail and obtain a URL.
|
||||
* The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload API Routes to upload the thumbnail and obtain a URL.
|
||||
*/
|
||||
thumbnail?: string
|
||||
/**
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import { SetRelation, Merge } from "../core/ModelUtils"
|
||||
|
||||
export interface StorePostCustomersCustomerAcceptClaimReq {
|
||||
/**
|
||||
* The claim token generated by previous request to the Claim Order endpoint.
|
||||
* The claim token generated by previous request to the Claim Order API Route.
|
||||
*/
|
||||
token: string
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface StorePostReturnsReq {
|
||||
*/
|
||||
quantity: number
|
||||
/**
|
||||
* The ID of the return reason. Return reasons can be retrieved from the List Return Reasons endpoint.
|
||||
* The ID of the return reason. Return reasons can be retrieved from the List Return Reasons API Route.
|
||||
*/
|
||||
reason_id?: string
|
||||
/**
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface StorePostSwapsReq {
|
||||
*/
|
||||
quantity: number
|
||||
/**
|
||||
* The ID of the reason of this return. Return reasons can be retrieved from the List Return Reasons endpoint.
|
||||
* The ID of the reason of this return. Return reasons can be retrieved from the List Return Reasons API Route.
|
||||
*/
|
||||
reason_id?: string
|
||||
/**
|
||||
|
||||
@@ -9,10 +9,10 @@ tags:
|
||||
- name: Apps Oauth
|
||||
description: |
|
||||
Some plugins may require to authenticate with third-party services and store authentication details, such as the authentication token. To do that, they can create an Oauth provider within the plugin that handles the authentication.
|
||||
The Apps Oauth endpoints allows admins to manage and generate token for an app using its oauth provider.
|
||||
The Apps Oauth API Routes allows admins to manage and generate token for an app using its oauth provider.
|
||||
- name: Auth
|
||||
description: |
|
||||
Authentication endpoints allow admin users to manage their session, such as login or log out.
|
||||
Authentication API Routes allow admin users to manage their session, such as login or log out.
|
||||
When an admin user is logged in, the cookie header is set indicating the admin's login session.
|
||||
externalDocs:
|
||||
description: How to implement user profiles
|
||||
@@ -20,14 +20,14 @@ tags:
|
||||
- name: Batch Jobs
|
||||
description: |
|
||||
A batch job is a task that is performed by the Medusa backend asynchronusly. For example, the Import Product feature is implemented using batch jobs.
|
||||
Batch Job endpoints allows admins to manage the batch jobs and their state.
|
||||
Batch Job API Routes allows admins to manage the batch jobs and their state.
|
||||
externalDocs:
|
||||
description: How to import products
|
||||
url: https://docs.medusajs.com/modules/products/admin/import-products
|
||||
- name: Currencies
|
||||
description: |
|
||||
A store can use unlimited currencies, and each region must be associated with at least one currency.
|
||||
Currencies are defined within the Medusa backend. Currency endpoints allow admins to list and update currencies.
|
||||
Currencies are defined within the Medusa backend. Currency API Routes allow admins to list and update currencies.
|
||||
externalDocs:
|
||||
description: How to manage currencies
|
||||
url: https://docs.medusajs.com/modules/regions-and-currencies/admin/manage-currencies
|
||||
@@ -47,7 +47,7 @@ tags:
|
||||
- name: Discounts
|
||||
description: |
|
||||
Admins can create discounts with conditions and rules, providing them with advanced settings for variety of cases.
|
||||
The Discount endpoints can be used to manage discounts, their conditions, resources, and more.
|
||||
The Discount API Routes can be used to manage discounts, their conditions, resources, and more.
|
||||
externalDocs:
|
||||
description: How to manage discounts
|
||||
url: https://docs.medusajs.com/modules/discounts/admin/manage-discounts
|
||||
@@ -60,7 +60,7 @@ tags:
|
||||
- name: Gift Cards
|
||||
description: |
|
||||
Admins can create gift cards and send them directly to customers, specifying options like their balance, region, and more.
|
||||
These gift cards are different than the saleable gift cards in a store, which are created and managed through Product endpoints.
|
||||
These gift cards are different than the saleable gift cards in a store, which are created and managed through Product API Routes.
|
||||
externalDocs:
|
||||
description: How to manage gift cards
|
||||
url: https://docs.medusajs.com/modules/gift-cards/admin/manage-gift-cards#manage-custom-gift-cards
|
||||
@@ -134,14 +134,14 @@ tags:
|
||||
- name: Product Variants
|
||||
description: |
|
||||
Product variants are the actual salable item in your store. Each variant is a combination of the different option values available on the product.
|
||||
Product variants can be managed through the Products endpoints.
|
||||
Product variants can be managed through the Products API Routes.
|
||||
externalDocs:
|
||||
description: How to manage product variants
|
||||
url: https://docs.medusajs.com/modules/products/admin/manage-products#manage-product-variants
|
||||
- name: Publishable API Keys
|
||||
description: |
|
||||
Publishable API Keys can be used to scope Store API calls with an API key, determining what resources are retrieved when querying the API.
|
||||
For example, a publishable API key can be associated with one or more sales channels. When it is passed in the header of a request to the List Product store endpoint,
|
||||
For example, a publishable API key can be associated with one or more sales channels. When it is passed in the header of a request to the List Product store API Route,
|
||||
the sales channels are inferred from the key and only products associated with those sales channels are retrieved.
|
||||
Admins can manage publishable API keys and their associated resources. Currently, only Sales Channels are supported as a resource.
|
||||
externalDocs:
|
||||
@@ -222,7 +222,7 @@ tags:
|
||||
url: https://docs.medusajs.com/modules/taxes/admin/manage-tax-rates
|
||||
- name: Uploads
|
||||
description: |
|
||||
The upload endpoints are used to upload any type of resources. For example, they can be used to upload CSV files that are used to import products into the store.
|
||||
The upload API Routes are used to upload any type of resources. For example, they can be used to upload CSV files that are used to import products into the store.
|
||||
externalDocs:
|
||||
description: How to upload CSV file when importing a product.
|
||||
url: https://docs.medusajs.com/modules/products/admin/import-products#1-upload-csv-file
|
||||
|
||||
@@ -8,7 +8,7 @@ info:
|
||||
tags:
|
||||
- name: Auth
|
||||
description: |
|
||||
Authentication endpoints allow customers to manage their session, such as login or log out.
|
||||
Authentication API Routes allow customers to manage their session, such as login or log out.
|
||||
When a customer is logged in, the cookie header is set indicating the customer's login session.
|
||||
externalDocs:
|
||||
description: How to implement customer profiles in your storefront
|
||||
@@ -29,14 +29,14 @@ tags:
|
||||
- name: Gift Cards
|
||||
description: |
|
||||
Customers can use gift cards during checkout to deduct the gift card's balance from the checkout total.
|
||||
The Gift Card endpoints allow retrieving a gift card's details by its code. A gift card can be applied to a cart using the Carts endpoints.
|
||||
The Gift Card API Routes allow retrieving a gift card's details by its code. A gift card can be applied to a cart using the Carts API Routes.
|
||||
externalDocs:
|
||||
description: How to use gift cards in a storefront
|
||||
url: https://docs.medusajs.com/modules/gift-cards/storefront/use-gift-cards
|
||||
- name: Orders
|
||||
description: |
|
||||
Orders are purchases made by customers, typically through a storefront.
|
||||
Orders are placed and created using the Carts endpoints. The Orders endpoints allow retrieving and claiming orders.
|
||||
Orders are placed and created using the Carts API Routes. The Orders API Routes allow retrieving and claiming orders.
|
||||
externalDocs:
|
||||
description: How to retrieve order details in a storefront
|
||||
url: https://docs.medusajs.com/modules/orders/storefront/retrieve-order-details
|
||||
@@ -53,7 +53,7 @@ tags:
|
||||
- name: Products
|
||||
description: |
|
||||
Products are saleable items in a store. This also includes [saleable gift cards](https://docs.medusajs.com/modules/gift-cards/storefront/use-gift-cards) in a store.
|
||||
Using these endpoints, you can filter products by categories, collections, sales channels, and more.
|
||||
Using these API Routes, you can filter products by categories, collections, sales channels, and more.
|
||||
externalDocs:
|
||||
description: How to show products in a storefront
|
||||
url: https://docs.medusajs.com/modules/products/storefront/show-products
|
||||
@@ -63,14 +63,14 @@ tags:
|
||||
- name: Product Categories
|
||||
description: |
|
||||
Products can be categoriezed into categories. A product can be associated more than one category.
|
||||
Using these endpoints, you can list or retrieve a category's details and products.
|
||||
Using these API Routes, you can list or retrieve a category's details and products.
|
||||
externalDocs:
|
||||
description: How to use product categories in a storefront
|
||||
url: https://docs.medusajs.com/modules/products/storefront/use-categories
|
||||
- name: Product Collections
|
||||
description: |
|
||||
A product collection is used to organize products for different purposes such as marketing or discount purposes. For example, you can create a Summer Collection.
|
||||
Using these endpoints, you can list or retrieve a collection's details and products.
|
||||
Using these API Routes, you can list or retrieve a collection's details and products.
|
||||
- name: Product Tags
|
||||
description: |
|
||||
Product tags are string values that can be used to filter products by.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* summary: "User Logout"
|
||||
* x-authenticated: true
|
||||
* description: "Delete the current session for the logged in user. This will only work if you're using Cookie session for authentication. If the API token is still passed in the header,
|
||||
* the user is still authorized to perform admin functionalities in other endpoints."
|
||||
* the user is still authorized to perform admin functionalities in other API Routes."
|
||||
* x-codegen:
|
||||
* method: deleteSession
|
||||
* x-codeSamples:
|
||||
|
||||
@@ -5,7 +5,7 @@ import { EntityManager } from "typeorm"
|
||||
* @oas [post] /admin/batch-jobs/{id}/confirm
|
||||
* operationId: "PostBatchJobsBatchJobConfirmProcessing"
|
||||
* summary: "Confirm a Batch Job"
|
||||
* description: "When a batch job is created, it is not executed automatically if `dry_run` is set to `true`. This endpoint confirms that the batch job should be executed."
|
||||
* description: "When a batch job is created, it is not executed automatically if `dry_run` is set to `true`. This API Route confirms that the batch job should be executed."
|
||||
* x-authenticated: true
|
||||
* parameters:
|
||||
* - (path) id=* {string} The ID of the batch job.
|
||||
|
||||
@@ -10,7 +10,7 @@ import { validator } from "../../../../utils/validator"
|
||||
* operationId: "PostBatchJobs"
|
||||
* summary: "Create a Batch Job"
|
||||
* description: "Create a Batch Job to be executed asynchronously in the Medusa backend. If `dry_run` is set to `true`, the batch job will not be executed until the it is confirmed,
|
||||
* which can be done using the Confirm Batch Job endpoint."
|
||||
* which can be done using the Confirm Batch Job API Route."
|
||||
* externalDocs:
|
||||
* description: "How to create a batch job"
|
||||
* url: "https://docs.medusajs.com/development/batch-jobs/create#create-batch-job"
|
||||
|
||||
@@ -54,7 +54,7 @@ import IsolateProductDomainFeatureFlag from "../../../../loaders/feature-flags/i
|
||||
* operationId: "PostProducts"
|
||||
* summary: "Create a Product"
|
||||
* x-authenticated: true
|
||||
* description: "Create a new Product. This endpoint can also be used to create a gift card if the `is_giftcard` field is set to `true`."
|
||||
* description: "Create a new Product. This API Route can also be used to create a gift card if the `is_giftcard` field is set to `true`."
|
||||
* requestBody:
|
||||
* content:
|
||||
* application/json:
|
||||
@@ -408,12 +408,12 @@ class ProductVariantReq {
|
||||
* type: boolean
|
||||
* default: true
|
||||
* images:
|
||||
* description: An array of images of the Product. Each value in the array is a URL to the image. You can use the upload endpoints to upload the image and obtain a URL.
|
||||
* description: An array of images of the Product. Each value in the array is a URL to the image. You can use the upload API Routes to upload the image and obtain a URL.
|
||||
* type: array
|
||||
* items:
|
||||
* type: string
|
||||
* thumbnail:
|
||||
* description: The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload endpoints to upload the thumbnail and obtain a URL.
|
||||
* description: The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload API Routes to upload the thumbnail and obtain a URL.
|
||||
* type: string
|
||||
* handle:
|
||||
* description: A unique handle to identify the Product by. If not provided, the kebab-case version of the product title will be used. This can be used as a slug in URLs.
|
||||
|
||||
@@ -434,12 +434,12 @@ class ProductVariantReq {
|
||||
* description: A flag to indicate if discounts can be applied to the Line Items generated from this Product
|
||||
* type: boolean
|
||||
* images:
|
||||
* description: An array of images of the Product. Each value in the array is a URL to the image. You can use the upload endpoints to upload the image and obtain a URL.
|
||||
* description: An array of images of the Product. Each value in the array is a URL to the image. You can use the upload API Routes to upload the image and obtain a URL.
|
||||
* type: array
|
||||
* items:
|
||||
* type: string
|
||||
* thumbnail:
|
||||
* description: The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload endpoints to upload the thumbnail and obtain a URL.
|
||||
* description: The thumbnail to use for the Product. The value is a URL to the thumbnail. You can use the upload API Routes to upload the thumbnail and obtain a URL.
|
||||
* type: string
|
||||
* handle:
|
||||
* description: A unique handle to identify the Product by. If not provided, the kebab-case version of the product title will be used. This can be used as a slug in URLs.
|
||||
|
||||
@@ -7,7 +7,7 @@ import { PaymentProvider } from "../../../../models"
|
||||
* @oas [get] /store/customers/me/payment-methods
|
||||
* operationId: GetCustomersCustomerPaymentMethods
|
||||
* summary: Get Saved Payment Methods
|
||||
* description: "Retrieve the logged-in customer's saved payment methods. This endpoint only works with payment providers created with the deprecated Payment Service interface.
|
||||
* description: "Retrieve the logged-in customer's saved payment methods. This API Route only works with payment providers created with the deprecated Payment Service interface.
|
||||
* The payment methods are saved using the Payment Service's third-party service, and not on the Medusa backend. So, they're retrieved from the third-party service."
|
||||
* x-authenticated: true
|
||||
* deprecated: true
|
||||
|
||||
@@ -7,7 +7,7 @@ import { EntityManager } from "typeorm"
|
||||
* @oas [post] /store/customers/password-token
|
||||
* operationId: PostCustomersCustomerPasswordToken
|
||||
* summary: Request Password Reset
|
||||
* description: "Create a reset password token to be used in a subsequent Reset Password endpoint. This emits the event `customer.password_reset`. If a notification provider is
|
||||
* description: "Create a reset password token to be used in a subsequent Reset Password API Route. This emits the event `customer.password_reset`. If a notification provider is
|
||||
* installed in the Medusa backend and is configured to handle this event, a notification to the customer, such as an email, may be sent with reset instructions."
|
||||
* externalDocs:
|
||||
* description: "How to reset password"
|
||||
|
||||
@@ -10,7 +10,7 @@ import { MedusaError } from "medusa-core-utils"
|
||||
* @oas [post] /store/customers/password-reset
|
||||
* operationId: PostCustomersResetPassword
|
||||
* summary: Reset Password
|
||||
* description: "Reset a Customer's password using a password token created by a previous request to the Request Password Reset endpoint. If the password token expired,
|
||||
* description: "Reset a Customer's password using a password token created by a previous request to the Request Password Reset API Route. If the password token expired,
|
||||
* you must create a new one."
|
||||
* externalDocs:
|
||||
* description: "How to reset password"
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
* @oas [post] /store/order-edits/{id}/complete
|
||||
* operationId: "PostOrderEditsOrderEditComplete"
|
||||
* summary: "Complete an Order Edit"
|
||||
* description: "Complete an Order Edit and reflect its changes on the original order. Any additional payment required must be authorized first using the Payment Collection endpoints."
|
||||
* description: "Complete an Order Edit and reflect its changes on the original order. Any additional payment required must be authorized first using the Payment Collection API Routes."
|
||||
* externalDocs:
|
||||
* description: "How to handle order edits in a storefront"
|
||||
* url: "https://docs.medusajs.com/modules/orders/storefront/handle-order-edits"
|
||||
|
||||
@@ -118,7 +118,7 @@ export default async (req, res) => {
|
||||
* - token
|
||||
* properties:
|
||||
* token:
|
||||
* description: "The claim token generated by previous request to the Claim Order endpoint."
|
||||
* description: "The claim token generated by previous request to the Claim Order API Route."
|
||||
* type: string
|
||||
*/
|
||||
export class StorePostCustomersCustomerAcceptClaimReq {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { TokenEvents } from "../../../../types/token"
|
||||
* @oas [post] /store/orders/batch/customer/token
|
||||
* operationId: "PostOrdersCustomerOrderClaim"
|
||||
* summary: "Claim Order"
|
||||
* description: "Allow the logged-in customer to claim ownership of one or more orders. This generates a token that can be used later on to verify the claim using the endpoint Verify Order Claim.
|
||||
* description: "Allow the logged-in customer to claim ownership of one or more orders. This generates a token that can be used later on to verify the claim using the Verify Order Claim API Route.
|
||||
* This also emits the event `order-update-token.created`. So, if you have a notification provider installed that handles this event and sends the customer a notification, such as an email,
|
||||
* the customer should receive instructions on how to finalize their claim ownership."
|
||||
* externalDocs:
|
||||
|
||||
@@ -12,7 +12,7 @@ import { defaultStoreCategoryScope } from "."
|
||||
* operationId: "GetProductCategories"
|
||||
* summary: "List Product Categories"
|
||||
* description: "Retrieve a list of product categories. The product categories can be filtered by fields such as `handle` or `q`. The product categories can also be paginated.
|
||||
* This endpoint can also be used to retrieve a product category by its handle."
|
||||
* This API Route can also be used to retrieve a product category by its handle."
|
||||
* x-featureFlag: "product_categories"
|
||||
* externalDocs:
|
||||
* description: "How to retrieve a product category by its handle"
|
||||
|
||||
@@ -32,7 +32,7 @@ import { defaultStoreProductRemoteQueryObject } from "./index"
|
||||
* summary: List Products
|
||||
* description: |
|
||||
* Retrieves a list of products. The products can be filtered by fields such as `id` or `q`. The products can also be sorted or paginated.
|
||||
* This endpoint can also be used to retrieve a product by its handle.
|
||||
* This API Route can also be used to retrieve a product by its handle.
|
||||
*
|
||||
* For accurate and correct pricing of the products based on the customer's context, it's highly recommended to pass fields such as
|
||||
* `region_id`, `currency_code`, and `cart_id` when available.
|
||||
|
||||
@@ -11,7 +11,7 @@ import { validator } from "../../../../utils/validator"
|
||||
* @oas [get] /store/regions
|
||||
* operationId: GetRegions
|
||||
* summary: List Regions
|
||||
* description: "Retrieve a list of regions. The regions can be filtered by fields such as `created_at`. The regions can also be paginated. This endpoint is useful to
|
||||
* description: "Retrieve a list of regions. The regions can be filtered by fields such as `created_at`. The regions can also be paginated. This API Route is useful to
|
||||
* show the customer all available regions to choose from."
|
||||
* externalDocs:
|
||||
* description: "How to use regions in a storefront"
|
||||
|
||||
@@ -280,7 +280,7 @@ class Item {
|
||||
* description: The quantity to return.
|
||||
* type: integer
|
||||
* reason_id:
|
||||
* description: The ID of the return reason. Return reasons can be retrieved from the List Return Reasons endpoint.
|
||||
* description: The ID of the return reason. Return reasons can be retrieved from the List Return Reasons API Route.
|
||||
* type: string
|
||||
* note:
|
||||
* description: A note to add to the item returned.
|
||||
|
||||
@@ -24,7 +24,7 @@ import { validator } from "../../../../utils/validator"
|
||||
* summary: Create a Swap
|
||||
* description: |
|
||||
* Create a Swap for an Order. This will also create a return and associate it with the swap. If a return shipping option is specified, the return will automatically be fulfilled.
|
||||
* To complete the swap, you must use the Complete Cart endpoint passing it the ID of the swap's cart.
|
||||
* To complete the swap, you must use the Complete Cart API Route passing it the ID of the swap's cart.
|
||||
*
|
||||
* An idempotency key will be generated if none is provided in the header `Idempotency-Key` and added to
|
||||
* the response. If an error occurs during swap creation or the request is interrupted for any reason, the swap creation can be retried by passing the idempotency
|
||||
@@ -316,7 +316,7 @@ class AdditionalItem {
|
||||
* description: The quantity to return.
|
||||
* type: integer
|
||||
* reason_id:
|
||||
* description: The ID of the reason of this return. Return reasons can be retrieved from the List Return Reasons endpoint.
|
||||
* description: The ID of the reason of this return. Return reasons can be retrieved from the List Return Reasons API Route.
|
||||
* type: string
|
||||
* note:
|
||||
* description: The note to add to the item being swapped.
|
||||
|
||||
@@ -6,9 +6,9 @@ import formatReportLink from "@/utils/format-report-link"
|
||||
|
||||
This API reference includes Medusa's Admin APIs, which are REST APIs exposed by the Medusa backend. They are typically used to perform admin functionalities or create an admin dashboard to access and manipulate your commerce store's data.
|
||||
|
||||
All endpoints are prefixed with `/admin`. So, during development, the endpoints will be available under the path `http://localhost:9000/admin`. For production, replace `http://localhost:9000` with your Medusa backend URL.
|
||||
All API Routes are prefixed with `/admin`. So, during development, the API Routes will be available under the path `http://localhost:9000/admin`. For production, replace `http://localhost:9000` with your Medusa backend URL.
|
||||
|
||||
There are different ways you can send requests to these endpoints, including:
|
||||
There are different ways you can send requests to these API Routes, including:
|
||||
|
||||
- Using Medusa's [JavaScript Client](https://docs.medusajs.com/js-client/overview)
|
||||
- Using the [Medusa React](https://docs.medusajs.com/medusa-react/overview) library
|
||||
@@ -40,7 +40,7 @@ Use a user's API Token to send authenticated requests.
|
||||
|
||||
#### How to Add API Token to a User
|
||||
|
||||
You can use the Update User endpoint to add or update the user's API token:
|
||||
You can use the Update User API Route to add or update the user's API token:
|
||||
|
||||
<CodeTabs
|
||||
tabs={[
|
||||
@@ -158,7 +158,7 @@ Use a JWT token to send authenticated requests. Authentication state is managed
|
||||
|
||||
#### How to Obtain the JWT Token
|
||||
|
||||
JWT tokens are obtained by sending a request to the [User Login (JWT) endpoint](#auth_posttoken) passing it the user's email and password in the request body. For example:
|
||||
JWT tokens are obtained by sending a request to the [User Login (JWT) API Route](#auth_posttoken) passing it the user's email and password in the request body. For example:
|
||||
|
||||
```bash
|
||||
curl -X POST 'https://medusa-url.com/admin/auth/token' \
|
||||
@@ -331,8 +331,8 @@ const App = () => {
|
||||
|
||||
## Expanding Fields
|
||||
|
||||
In many endpoints you'll find an `expand` query parameter that can be passed
|
||||
to the endpoint. You can use the `expand` query parameter to unpack an
|
||||
In many API Routes you'll find an `expand` query parameter that can be passed
|
||||
to the API Route. You can use the `expand` query parameter to unpack an
|
||||
entity's relations and return them in the response.
|
||||
|
||||
|
||||
@@ -544,8 +544,8 @@ relations like `collection`.
|
||||
## Selecting Fields
|
||||
|
||||
|
||||
In many endpoints you'll find a `fields` query parameter that can be passed
|
||||
to the endpoint. You can use the `fields` query parameter to specify which
|
||||
In many API Routes you'll find a `fields` query parameter that can be passed
|
||||
to the API Route. You can use the `fields` query parameter to specify which
|
||||
fields in the entity should be returned in the response.
|
||||
|
||||
|
||||
@@ -876,7 +876,7 @@ export default Products`,
|
||||
|
||||
|
||||
This section covers how to pass some common data types as query parameters.
|
||||
This is useful if you're sending requests to the API endpoints and not using
|
||||
This is useful if you're sending requests to the API routes and not using
|
||||
the JS Client. For example, when using cURL or Postman.
|
||||
|
||||
|
||||
@@ -1028,7 +1028,7 @@ curl -g "http://localhost:9000/admin/products?created_at[lt]=2023-02-17&created_
|
||||
### Query Parameters
|
||||
|
||||
|
||||
In listing endpoints, such as list customers or list products, you can control the pagination using the query parameters `limit` and `offset`.
|
||||
In listing API Routes, such as list customers or list products, you can control the pagination using the query parameters `limit` and `offset`.
|
||||
|
||||
|
||||
`limit` is used to specify the maximum number of items that can be return in the response. `offset` is used to specify how many items to skip before returning the resulting entities.
|
||||
@@ -1037,7 +1037,7 @@ In listing endpoints, such as list customers or list products, you can control t
|
||||
You can use the `offset` query parameter to change between pages. For example, if the limit is 50, at page 1 the offset should be 0; at page 2 the offset should be 50, and so on.
|
||||
|
||||
|
||||
For example, to limit the number of products returned in the List Products endpoint:
|
||||
For example, to limit the number of products returned in the List Products API Route:
|
||||
|
||||
<CodeTabs
|
||||
tabs={[
|
||||
@@ -1095,7 +1095,7 @@ export default Products`,
|
||||
### Response Fields
|
||||
|
||||
|
||||
In the response of listing endpoints, aside from the entities retrieved,
|
||||
In the response of listing API Routes, aside from the entities retrieved,
|
||||
there are three pagination-related fields returned: `count`, `limit`, and
|
||||
`offset`.
|
||||
|
||||
@@ -1116,7 +1116,7 @@ For example, if the `count` is 100 and the `limit` is 50, you can divide the
|
||||
### Sort Order
|
||||
|
||||
|
||||
The `order` field available on endpoints supporting pagination allows you to
|
||||
The `order` field available on API Routes supporting pagination allows you to
|
||||
sort the retrieved items by an attribute of that item. For example, you can
|
||||
sort products by their `created_at` attribute by setting `order` to
|
||||
`created_at`:
|
||||
|
||||
@@ -7,9 +7,9 @@ import formatReportLink from "@/utils/format-report-link"
|
||||
|
||||
This API reference includes Medusa's Store APIs, which are REST APIs exposed by the Medusa backend. They are typically used to create a storefront for your commerce store, such as a webshop or a commerce mobile app.
|
||||
|
||||
All endpoints are prefixed with `/store`. So, during development, the endpoints will be available under the path `http://localhost:9000/store`. For production, replace `http://localhost:9000` with your Medusa backend URL.
|
||||
All API Routes are prefixed with `/store`. So, during development, the API Routes will be available under the path `http://localhost:9000/store`. For production, replace `http://localhost:9000` with your Medusa backend URL.
|
||||
|
||||
There are different ways you can send requests to these endpoints, including:
|
||||
There are different ways you can send requests to these API Routes, including:
|
||||
|
||||
- Using Medusa's [JavaScript Client](https://docs.medusajs.com/js-client/overview)
|
||||
- Using the [Medusa React](https://docs.medusajs.com/medusa-react/overview) library
|
||||
@@ -41,7 +41,7 @@ Use a JWT token to send authenticated requests. Authentication state is managed
|
||||
|
||||
#### How to Obtain the JWT Token
|
||||
|
||||
JWT tokens are obtained by sending a request to the [Customer Login (JWT) endpoint](#auth_authtoken) passing it the customer's email and password in the request body. For example:
|
||||
JWT tokens are obtained by sending a request to the [Customer Login (JWT) API Route](#auth_authtoken) passing it the customer's email and password in the request body. For example:
|
||||
|
||||
```bash
|
||||
curl -X POST 'https://medusa-url.com/store/auth/token' \
|
||||
@@ -297,8 +297,8 @@ const App = () => {
|
||||
## Expanding Fields
|
||||
|
||||
|
||||
In many endpoints you'll find an `expand` query parameter that can be passed
|
||||
to the endpoint. You can use the `expand` query parameter to unpack an
|
||||
In many API Routes you'll find an `expand` query parameter that can be passed
|
||||
to the API Route. You can use the `expand` query parameter to unpack an
|
||||
entity's relations and return them in the response.
|
||||
|
||||
|
||||
@@ -501,8 +501,8 @@ relations like `collection`.
|
||||
## Selecting Fields
|
||||
|
||||
|
||||
In many endpoints you'll find a `fields` query parameter that can be passed
|
||||
to the endpoint. You can use the `fields` query parameter to specify which
|
||||
In many API Routes you'll find a `fields` query parameter that can be passed
|
||||
to the API Route. You can use the `fields` query parameter to specify which
|
||||
fields in the entity should be returned in the response.
|
||||
|
||||
|
||||
@@ -823,7 +823,7 @@ export default Products`,
|
||||
|
||||
|
||||
This section covers how to pass some common data types as query parameters.
|
||||
This is useful if you're sending requests to the API endpoints and not using
|
||||
This is useful if you're sending requests to the API Routes and not using
|
||||
our JS Client. For example, when using cURL or Postman.
|
||||
|
||||
|
||||
@@ -966,7 +966,7 @@ curl -g "http://localhost:9000/store/products?created_at[lt]=2023-02-17&created_
|
||||
### Query Parameters
|
||||
|
||||
|
||||
In listing endpoints, such as list customers or list products, you can
|
||||
In listing API Routes, such as list customers or list products, you can
|
||||
control the pagination using the query parameters `limit` and `offset`.
|
||||
|
||||
|
||||
@@ -981,7 +981,7 @@ offset should be `50`, and so on.
|
||||
|
||||
|
||||
For example, to limit the number of products returned in the List Products
|
||||
endpoint:
|
||||
API Route:
|
||||
|
||||
<CodeTabs
|
||||
tabs={[
|
||||
@@ -1037,7 +1037,7 @@ export default Products`,
|
||||
### Response Fields
|
||||
|
||||
|
||||
In the response of listing endpoints, aside from the entities retrieved,
|
||||
In the response of listing API Routes, aside from the entities retrieved,
|
||||
there are three pagination-related fields returned: `count`, `limit`, and
|
||||
`offset`.
|
||||
|
||||
@@ -1058,7 +1058,7 @@ For example, if the `count` is 100 and the `limit` is 50, you can divide the
|
||||
### Sort Order
|
||||
|
||||
|
||||
The `order` field available on endpoints supporting pagination allows you to
|
||||
The `order` field available on API Routes supporting pagination allows you to
|
||||
sort the retrieved items by an attribute of that item. For example, you can
|
||||
sort products by their `created_at` attribute by setting `order` to
|
||||
`created_at`:
|
||||
|
||||
@@ -72,7 +72,7 @@ const TagsOperationDescriptionSection = ({
|
||||
reportLink={formatReportLink(area, operation.summary)}
|
||||
className="!my-2"
|
||||
vertical={true}
|
||||
question="Did this endpoint run successfully?"
|
||||
question="Did this API Route run successfully?"
|
||||
/>
|
||||
{operation.externalDocs && (
|
||||
<>
|
||||
|
||||
@@ -33,7 +33,7 @@ const TagPaths = ({ tag, className }: TagPathsProps) => {
|
||||
const { loading } = useLoading()
|
||||
// if paths are already loaded since through
|
||||
// the expanded field, they're loaded directly
|
||||
// otherwise, they're loaded using the API endpoint
|
||||
// otherwise, they're loaded using the API route
|
||||
let paths: PathsObject =
|
||||
baseSpecs?.expandedTags &&
|
||||
Object.hasOwn(baseSpecs.expandedTags, tagSlugName)
|
||||
|
||||
@@ -13,11 +13,11 @@ tags:
|
||||
that, they can create an Oauth provider within the plugin that handles the
|
||||
authentication.
|
||||
|
||||
The Apps Oauth endpoints allows admins to manage and generate token for an
|
||||
The Apps Oauth API Routes allows admins to manage and generate token for an
|
||||
app using its oauth provider.
|
||||
- name: Auth
|
||||
description: >
|
||||
Authentication endpoints allow admin users to manage their session, such
|
||||
Authentication API Routes allow admin users to manage their session, such
|
||||
as login or log out.
|
||||
|
||||
When an admin user is logged in, the cookie header is set indicating the
|
||||
@@ -31,7 +31,7 @@ tags:
|
||||
asynchronusly. For example, the Import Product feature is implemented
|
||||
using batch jobs.
|
||||
|
||||
Batch Job endpoints allows admins to manage the batch jobs and their
|
||||
Batch Job API Routes allows admins to manage the batch jobs and their
|
||||
state.
|
||||
externalDocs:
|
||||
description: How to import products
|
||||
@@ -41,7 +41,7 @@ tags:
|
||||
A store can use unlimited currencies, and each region must be associated
|
||||
with at least one currency.
|
||||
|
||||
Currencies are defined within the Medusa backend. Currency endpoints allow
|
||||
Currencies are defined within the Medusa backend. Currency API Routes allow
|
||||
admins to list and update currencies.
|
||||
externalDocs:
|
||||
description: How to manage currencies
|
||||
@@ -69,7 +69,7 @@ tags:
|
||||
Admins can create discounts with conditions and rules, providing them with
|
||||
advanced settings for variety of cases.
|
||||
|
||||
The Discount endpoints can be used to manage discounts, their conditions,
|
||||
The Discount API Routes can be used to manage discounts, their conditions,
|
||||
resources, and more.
|
||||
externalDocs:
|
||||
description: How to manage discounts
|
||||
@@ -87,7 +87,7 @@ tags:
|
||||
specifying options like their balance, region, and more.
|
||||
|
||||
These gift cards are different than the saleable gift cards in a store,
|
||||
which are created and managed through Product endpoints.
|
||||
which are created and managed through Product API Routes.
|
||||
externalDocs:
|
||||
description: How to manage gift cards
|
||||
url: >-
|
||||
@@ -195,7 +195,7 @@ tags:
|
||||
Product variants are the actual salable item in your store. Each variant
|
||||
is a combination of the different option values available on the product.
|
||||
|
||||
Product variants can be managed through the Products endpoints.
|
||||
Product variants can be managed through the Products API Routes.
|
||||
externalDocs:
|
||||
description: How to manage product variants
|
||||
url: >-
|
||||
@@ -207,7 +207,7 @@ tags:
|
||||
|
||||
For example, a publishable API key can be associated with one or more
|
||||
sales channels. When it is passed in the header of a request to the List
|
||||
Product store endpoint,
|
||||
Product store API Route,
|
||||
|
||||
the sales channels are inferred from the key and only products associated
|
||||
with those sales channels are retrieved.
|
||||
@@ -330,7 +330,7 @@ tags:
|
||||
url: https://docs.medusajs.com/modules/taxes/admin/manage-tax-rates
|
||||
- name: Uploads
|
||||
description: >
|
||||
The upload endpoints are used to upload any type of resources. For
|
||||
The upload API Routes are used to upload any type of resources. For
|
||||
example, they can be used to upload CSV files that are used to import
|
||||
products into the store.
|
||||
externalDocs:
|
||||
|
||||
@@ -8,7 +8,7 @@ info:
|
||||
tags:
|
||||
- name: Auth
|
||||
description: >
|
||||
Authentication endpoints allow customers to manage their session, such as
|
||||
Authentication API Routes allow customers to manage their session, such as
|
||||
login or log out.
|
||||
|
||||
When a customer is logged in, the cookie header is set indicating the
|
||||
@@ -40,8 +40,8 @@ tags:
|
||||
Customers can use gift cards during checkout to deduct the gift card's
|
||||
balance from the checkout total.
|
||||
|
||||
The Gift Card endpoints allow retrieving a gift card's details by its
|
||||
code. A gift card can be applied to a cart using the Carts endpoints.
|
||||
The Gift Card API Routes allow retrieving a gift card's details by its
|
||||
code. A gift card can be applied to a cart using the Carts API Routes.
|
||||
externalDocs:
|
||||
description: How to use gift cards in a storefront
|
||||
url: https://docs.medusajs.com/modules/gift-cards/storefront/use-gift-cards
|
||||
@@ -49,8 +49,8 @@ tags:
|
||||
description: >
|
||||
Orders are purchases made by customers, typically through a storefront.
|
||||
|
||||
Orders are placed and created using the Carts endpoints. The Orders
|
||||
endpoints allow retrieving and claiming orders.
|
||||
Orders are placed and created using the Carts API Routes. The Orders
|
||||
API Routes allow retrieving and claiming orders.
|
||||
externalDocs:
|
||||
description: How to retrieve order details in a storefront
|
||||
url: >-
|
||||
@@ -75,7 +75,7 @@ tags:
|
||||
cards](https://docs.medusajs.com/modules/gift-cards/storefront/use-gift-cards)
|
||||
in a store.
|
||||
|
||||
Using these endpoints, you can filter products by categories, collections,
|
||||
Using these API Routes, you can filter products by categories, collections,
|
||||
sales channels, and more.
|
||||
externalDocs:
|
||||
description: How to show products in a storefront
|
||||
@@ -89,7 +89,7 @@ tags:
|
||||
Products can be categoriezed into categories. A product can be associated
|
||||
more than one category.
|
||||
|
||||
Using these endpoints, you can list or retrieve a category's details and
|
||||
Using these API Routes, you can list or retrieve a category's details and
|
||||
products.
|
||||
externalDocs:
|
||||
description: How to use product categories in a storefront
|
||||
@@ -100,7 +100,7 @@ tags:
|
||||
such as marketing or discount purposes. For example, you can create a
|
||||
Summer Collection.
|
||||
|
||||
Using these endpoints, you can list or retrieve a collection's details and
|
||||
Using these API Routes, you can list or retrieve a collection's details and
|
||||
products.
|
||||
- name: Product Tags
|
||||
description: |
|
||||
|
||||
+1174
-1562
File diff suppressed because one or more lines are too long
@@ -356,9 +356,9 @@ const CustomPage = () => {
|
||||
export default CustomPage
|
||||
```
|
||||
|
||||
### Custom Endpoints
|
||||
### Custom API Routes
|
||||
|
||||
You can also use `medusa-react` to interact with custom endpoints using [Custom Hooks utility functions](../medusa-react/overview.mdx#custom-hooks).
|
||||
You can also use `medusa-react` to interact with custom API Routes using [Custom Hooks utility functions](../medusa-react/overview.mdx#custom-hooks).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -337,9 +337,9 @@ export const config: SettingConfig = {
|
||||
export default CustomSettingPage
|
||||
```
|
||||
|
||||
### Custom Endpoints
|
||||
### Custom API Routes
|
||||
|
||||
You can also use `medusa-react` to interact with custom endpoints using [Custom Hooks utility functions](../medusa-react/overview.mdx#custom-hooks).
|
||||
You can also use `medusa-react` to interact with custom API Routes using [Custom Hooks utility functions](../medusa-react/overview.mdx#custom-hooks).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1270,9 +1270,9 @@ export const config: WidgetConfig = {
|
||||
export default ProductWidget
|
||||
```
|
||||
|
||||
### Custom Endpoints
|
||||
### Custom API Routes
|
||||
|
||||
You can also use `medusa-react` to interact with custom endpoints using the [createCustomAdminHooks utility function](../medusa-react/overview.mdx#custom-hooks).
|
||||
You can also use `medusa-react` to interact with custom API Routes using the [createCustomAdminHooks utility function](../medusa-react/overview.mdx#custom-hooks).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ Documentation pages under the `www/apps/docs/content/references` directory are g
|
||||
The API reference's content is split into two types:
|
||||
|
||||
1. Static content, which are the content related to getting started, expanding fields, and more. These are located in the [www/apps/api-reference/app/_mdx](https://github.com/medusajs/medusa/tree/develop/www/apps/api-reference/app/_mdx) directory. They are MDX files.
|
||||
2. OpenAPI specs that are shown to developers when checking the reference of an endpoint. These are automatically generated from comments on endpoints. So, if you find issues in them or want to make improvements, you have to find the endpoint under the [`packages/medusa/src/api`](https://github.com/medusajs/medusa/tree/develop/packages/medusa/src/api) directory and make changes to its comments.
|
||||
2. OpenAPI specs that are shown to developers when checking the reference of an API Route. These are automatically generated from comments on API Routes. So, if you find issues in them or want to make improvements, you have to find the API Routes under the [`packages/medusa/src/api`](https://github.com/medusajs/medusa/tree/develop/packages/medusa/src/api) directory and make changes to its comments.
|
||||
|
||||
### Medusa UI Documentation
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ Once the build process is complete, a new deployment with the infrastructure res
|
||||
|
||||
## Test the Backend
|
||||
|
||||
After the deployment is finished, navigate to Resources → [AppName] (Medusa in this example) → Overview. Then, under the Resource Outputs section you should see the "AccessUrl". This is the backend's URL that you can use to access API endpoints and test them. You can try getting the list of products using the endpoint `<AccessUrl>/store/products`.
|
||||
After the deployment is finished, navigate to Resources → [AppName] (Medusa in this example) → Overview. Then, under the Resource Outputs section you should see the "AccessUrl". This is the backend's URL that you can use to access API Routes and test them. You can try getting the list of products using the API Route `<AccessUrl>/store/products`.
|
||||
|
||||
### Health Route
|
||||
|
||||
|
||||
+7
-2
@@ -1,5 +1,4 @@
|
||||
---
|
||||
description: 'Learn how to add a middleware in Medusa. A middleware is a function that has access to the request and response objects and can be used to perform actions around an endpoint.'
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
@@ -7,10 +6,16 @@ import Troubleshooting from '@site/src/components/Troubleshooting'
|
||||
import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md'
|
||||
import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md'
|
||||
|
||||
# Middlewares
|
||||
# Middlewares - Express Endpoints Approach
|
||||
|
||||
In this document, you’ll learn how to add a middleware to an existing or custom route in Medusa.
|
||||
|
||||
:::note
|
||||
|
||||
Following v1.17.2 of `@medusajs/medusa`, it's highly recommended to use the [middlewares.ts file](./add-middleware.mdx) to create middlewares instead. Future versions of Medusa may drop support of this approach.
|
||||
|
||||
:::
|
||||
|
||||
## Overview
|
||||
|
||||
As the Medusa backend is built on top of [Express](https://expressjs.com/), Express’s features can be utilized during your development with Medusa.
|
||||
@@ -0,0 +1,214 @@
|
||||
---
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
import Troubleshooting from '@site/src/components/Troubleshooting'
|
||||
import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md'
|
||||
import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md'
|
||||
|
||||
# Middlewares
|
||||
|
||||
In this document, you’ll learn how to add a middleware to existing or custom API Routes in Medusa.
|
||||
|
||||
:::tip
|
||||
|
||||
v1.17.2 of `@medusajs/medusa` introduced a new approach to creating middlewares using a single `middlewares.ts` file. You can still use the [Express Router Approach](./add-middleware-express-route.mdx), however, it's highly recommended that you start using this new approach.
|
||||
|
||||
:::
|
||||
|
||||
## Basic Implementation
|
||||
|
||||
```ts title=src/api/middlewares.ts
|
||||
import type { MiddlewaresConfig } from "@medusajs/medusa"
|
||||
import type {
|
||||
MedusaNextFunction,
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
const storeMiddleware = (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse,
|
||||
next: MedusaNextFunction
|
||||
) => {
|
||||
// do something
|
||||
next()
|
||||
}
|
||||
|
||||
export const config: MiddlewaresConfig = {
|
||||
routes: [
|
||||
{
|
||||
matcher: "/store/*",
|
||||
middlewares: [storeMiddleware],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
A middleware is a function that has access to the `MedusaRequest` and `MedusaResponse` objects that are passed to API Route method handlers.
|
||||
|
||||
Middlewares are used to perform an action when a request is sent to an API Route, or modify the response of an API route, among other usages.
|
||||
|
||||
### middlewares.ts File
|
||||
|
||||
Middlewares are defined in the `src/api/middlewares.ts` file. This file must expose a config object of type `MiddlewaresConfig` imported from `@medusajs/medusa`.
|
||||
|
||||
This object accepts a parameter `routes`, whose value is an array of middleware route objects. Each middleware route object accepts the following properties:
|
||||
|
||||
- The `matcher` property accepts a string or a regular expression that will be used to check whether the middlewares should be applied on a API Routes.
|
||||
- The `middlewares` property is an array of middlewares that should be applied on API Routes matching the pattern specified in `matcher`.
|
||||
|
||||
---
|
||||
|
||||
## Build Files
|
||||
|
||||
Similar to custom API Routes, you must transpile the files under `src` into the `dist` directory for the backend to load them.
|
||||
|
||||
To do that, run the following command before running the Medusa backend:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can then test that the middleware is working by running the backend.
|
||||
|
||||
---
|
||||
|
||||
## Register New Resources in Dependency Container
|
||||
|
||||
In some cases, you may need to register a resource to use within your commerce application. For example, you may want to register the logged-in user to access it in other resources, such as services. You can do that in your middleware.
|
||||
|
||||
:::tip
|
||||
|
||||
If you want to register a logged-in user and access it in your resources, you can check out [this example guide](./example-logged-in-user.mdx).
|
||||
|
||||
:::
|
||||
|
||||
To register a new resource in the dependency container, use the `MedusaRequest` object's `scope.register` method. It accepts an object, where each key is the name to be registered in the dependency container, and its value is an object that has a `resolve` property.
|
||||
|
||||
The `resolve`'s value is a function that returns the resource to be registered in the dependency container.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/middlewares.ts
|
||||
import type { MiddlewaresConfig } from "@medusajs/medusa"
|
||||
import type {
|
||||
MedusaNextFunction,
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
const customResource = (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse,
|
||||
next: MedusaNextFunction) => {
|
||||
req.scope.register({
|
||||
customResource: {
|
||||
resolve: () => "my custom resource",
|
||||
},
|
||||
})
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
export const config: MiddlewaresConfig = {
|
||||
routes: [
|
||||
{
|
||||
matcher: "/store/*",
|
||||
middlewares: [customResource],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
You can then load this new resource within other resources. For example, to load it in a service:
|
||||
|
||||
<!-- eslint-disable prefer-rest-params -->
|
||||
|
||||
```ts title=src/services/custom-service.ts
|
||||
import { TransactionBaseService } from "@medusajs/medusa"
|
||||
|
||||
class CustomService extends TransactionBaseService {
|
||||
|
||||
constructor(container, options) {
|
||||
super(...arguments)
|
||||
|
||||
// use the registered resource.
|
||||
try {
|
||||
container.customResource
|
||||
} catch (e) {
|
||||
// avoid errors when the backend first loads
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default CustomService
|
||||
```
|
||||
|
||||
:::note
|
||||
|
||||
Make sure to wrap your usage of the new resource in a try-catch block when you use it in a constructor. This is to avoid errors that can arise when the backend first loads, as the resource isn't registered yet.
|
||||
|
||||
:::
|
||||
|
||||
### Note About Services Lifetime
|
||||
|
||||
If you want to access new registrations in the dependency container within a service, you must set the lifetime of the service either to `Lifetime.SCOPED` or `Lifetime.TRANSIENT`. Services that have a `Lifetime.SINGLETON` lifetime can't access new registrations since they're resolved and cached in the root dependency container beforehand. You can learn more in the [Create Services documentation](../services/create-service.mdx#service-life-time).
|
||||
|
||||
For custom services, no additional action is required as the default lifetime is `Lifetime.SCOPED`. However, if you extend a core service, you must change the lifetime since the default lifetime for core services is `Lifetime.SINGLETON`.
|
||||
|
||||
For example:
|
||||
|
||||
<!-- eslint-disable prefer-rest-params -->
|
||||
|
||||
```ts
|
||||
import { Lifetime } from "awilix"
|
||||
import {
|
||||
ProductService as MedusaProductService,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
// extending ProductService from the core
|
||||
class ProductService extends MedusaProductService {
|
||||
// The default life time for a core service is SINGLETON
|
||||
static LIFE_TIME = Lifetime.SCOPED
|
||||
|
||||
constructor(container, options) {
|
||||
super(...arguments)
|
||||
|
||||
// use the registered resource.
|
||||
try {
|
||||
container.customResource
|
||||
} catch (e) {
|
||||
// avoid errors when the backend first loads
|
||||
}
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
export default ProductService
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<Troubleshooting
|
||||
sections={[
|
||||
{
|
||||
title: 'AwilixResolutionError: Could Not Resolve X',
|
||||
content: <ServiceLifetimeSection />
|
||||
},
|
||||
{
|
||||
title: 'AwilixResolutionError: Could Not Resolve X (Custom Registration)',
|
||||
content: <CustomRegistrationSection />
|
||||
}
|
||||
]}
|
||||
/>
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Store API reference](https://docs.medusajs.com/api/store)
|
||||
- [Admin API reference](https://docs.medusajs.com/api/admin)
|
||||
+7
-10
@@ -1,22 +1,19 @@
|
||||
---
|
||||
description: 'Learn how to create endpoints in Medusa. This guide also includes how to add CORS configurations, creating multiple endpoints, adding protected routes, and more.'
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
# How to Create Endpoints
|
||||
# Create Express Endpoint
|
||||
|
||||
In this document, you’ll learn how to create endpoints in Medusa.
|
||||
In this document, you’ll learn how to create express endpoints in Medusa.
|
||||
|
||||
## Overview
|
||||
:::note
|
||||
|
||||
Custom endpoints are created under the `src/api` directory in your Medusa Backend. They're defined in a TypeScript or JavaScript file named `index` (for example, `index.ts`). This file should export a function that returns an Express router or an array of routes and middlewares.
|
||||
Following v1.17.2 of `@medusajs/medusa`, it's highly recommended to use the [API Routes](./create.mdx) instead. Future versions of Medusa may drop support of Express Endpoints.
|
||||
|
||||
To consume the custom endpoints in your Medusa backend, you must transpile them with the `build` command before starting your backend.
|
||||
|
||||
---
|
||||
:::
|
||||
|
||||
## Basic Implementation
|
||||
|
||||
@@ -61,7 +58,7 @@ npm run build
|
||||
|
||||
## Defining Multiple Routes or Middlewares
|
||||
|
||||
Instead of returning an Express router in the function, you can return an array of routes and [middlewares](./add-middleware.mdx).
|
||||
Instead of returning an Express router in the function, you can return an array of routes and [middlewares](./add-middleware-express-route.mdx).
|
||||
|
||||
For example:
|
||||
|
||||
@@ -419,7 +416,7 @@ export default (rootDirectory) => {
|
||||
|
||||
As Medusa uses v4 of Express, you need to manually handle errors thrown asynchronously as explained in [Express's documentation](https://expressjs.com/en/guide/error-handling.html).
|
||||
|
||||
You can use [middlewares](./add-middleware.mdx) to handle errors. You can also use middlewares defined by Medusa, which ensure that your error handling is consistent across your Medusa backend.
|
||||
You can use [middlewares](./add-middleware-express-route.mdx) to handle errors. You can also use middlewares defined by Medusa, which ensure that your error handling is consistent across your Medusa backend.
|
||||
|
||||
:::note
|
||||
|
||||
@@ -0,0 +1,744 @@
|
||||
---
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
# How to Create an API Route
|
||||
|
||||
In this document, you’ll learn how to create API Routes in Medusa.
|
||||
|
||||
:::tip
|
||||
|
||||
v1.17.2 of `@medusajs/medusa` introduced API Routes to replace Express endpoints. You can still use the [Express endpoints approach](./create-express-route.mdx), however, it's highly recommended that you start using API Routes.
|
||||
|
||||
:::
|
||||
|
||||
## Basic Implementation
|
||||
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const GET = (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
res.json({
|
||||
message: "[GET] Hello world!",
|
||||
})
|
||||
}
|
||||
|
||||
export const POST = (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
res.json({
|
||||
message: "[POST] Hello world!",
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### API Route Path
|
||||
|
||||
Custom API Routes must be created in a file named `route.ts` or `route.js` under the `src/api` directory of your Medusa backend or plugin. The API Route's path will be the same as the path of its corresponding `route.ts` file relative to `src/api`.
|
||||
|
||||
For example, if you're creating the API route `store/custom`, you must create the file `src/api/store/custom/route.ts`.
|
||||
|
||||
### API Route Method
|
||||
|
||||
`route.ts` can export at least one of the following method handler functions: `GET`, `POST`, `DELETE`, `PUT`, `PATCH`, `OPTIONS`, and `HEAD`. Defining these method handlers adds a new API Route for the corresponding HTTP method at the same path.
|
||||
|
||||
Each of these method handler functions receives two parameters: the `MedusaRequest` which extends Express's [Request](https://expressjs.com/en/api.html#req), and the `MedusaResponse` which extends [Response](https://expressjs.com/en/api.html#res). Both are imported from `@medusajs/medusa`.
|
||||
|
||||
In the example above, `GET` and `POST` API Routes will be added at the `store/custom` path.
|
||||
|
||||
---
|
||||
|
||||
## Building Files
|
||||
|
||||
Custom API Routes must be transpiled and moved to the `dist` directory before you can start consuming them. When you run your backend using either the `medusa develop` or `npx medusa develop` commands, it watches the files under `src` for any changes, then triggers the `build` command and restarts the server.
|
||||
|
||||
However, the build isn't triggered when the backend first starts running, and it's never triggered when the `medusa start` or `npx medusa start` commands are used.
|
||||
|
||||
So, make sure to run the `build` command before starting the backend and testing out your API Routes:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Medusa API Routes Path Convention
|
||||
|
||||
Although your API Route can be under any path you wish, the Medusa backend uses the following conventions:
|
||||
|
||||
- All storefront REST APIs are prefixed by `/store`. For example, the `/store/products` API Route lets you retrieve the products to display them on your storefront.
|
||||
- All admin REST APIs are prefixed by `/admin`. For example, the `/admin/products` API Route lets you retrieve the products to display them on your admin.
|
||||
|
||||
---
|
||||
|
||||
## Path Parameters
|
||||
|
||||
If your API Route accepts a path parameter, you can place its route file inside a directory with the name `[<PARAMETER_NAME>]`, where `<PARAMETER_NAME>` is the name of your parameter.
|
||||
|
||||
For example, to add an API Route at the path `store/custom/[id]`, create the route file at `src/api/store/custom/[id]/route.ts`.
|
||||
|
||||
You can access a path parameter's value in method handlers using the `MedusaRequest` object's `params` property, which is an object. Each of the `params` keys is a path parameter's name, and its value is the supplied value when sending the request to the API route.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/store/custom/[id]/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export function GET(
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) {
|
||||
const id = req.params.id
|
||||
|
||||
// do something with the ID.
|
||||
}
|
||||
```
|
||||
|
||||
An API Route can have more than one path parameter, but each path parameter's nam is unique. If the same path parameter name is used more than once in the same route path, it results in an error and the Medusa Backend won't register the API Route.
|
||||
|
||||
For example, if your API route accepts an author ID and a post ID, the path to your route file can be `src/api/author/[id]/posts/[post_id]/route.ts`. You can then use the `MedusaRequest` object's `params.id` and `params.post_id` to access the values of the path parameters.
|
||||
|
||||
---
|
||||
|
||||
## CORS Configuration
|
||||
|
||||
CORS configurations are automatically added to custom API Routes defined under the `/store` or `/admin` path prefixes based on the [store_cors and admin_cors configurations](../backend/configurations.md#admin_cors-and-store_cors) respectively.
|
||||
|
||||
To add CORS configurations to custom API routes under other path prefixes, or override the CORS configurations added by default, define a [middleware](./add-middleware.mdx) on your API routes and pass it the `cors` middleware. For example:
|
||||
|
||||
```ts title=src/api/middlewares.ts
|
||||
import type {
|
||||
MiddlewaresConfig,
|
||||
} from "@medusajs/medusa"
|
||||
import cors from "cors"
|
||||
|
||||
export const config: MiddlewaresConfig = {
|
||||
routes: [
|
||||
{
|
||||
matcher: "/custom/*",
|
||||
middlewares: [
|
||||
cors({
|
||||
origin: "*",
|
||||
credentials: true,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Parse Request Body Parameters
|
||||
|
||||
By default, the Medusa backend parses the body of all requests sent to your API Routes with the `Content-Type` header set to `application/json` to a JavaScript object. Then, the parsed data is attached to the `MedusaRequest` object's `body` property, which is an object.
|
||||
|
||||
Each of the `body`'s keys are a name of the request body parameters, and its value is the passed value in the request body.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const POST = (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const name = req.body.name
|
||||
|
||||
// do something with the data...
|
||||
}
|
||||
```
|
||||
|
||||
If you want to parse other content types, such as `application/x-www-form-urlencoded`, you have to add a [middleware](./add-middleware.mdx) to your API routes that parses that body type.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/middlewares.ts
|
||||
import type {
|
||||
MiddlewaresConfig,
|
||||
} from "@medusajs/medusa"
|
||||
import {
|
||||
urlencoded,
|
||||
} from "body-parser"
|
||||
|
||||
export const config: MiddlewaresConfig = {
|
||||
routes: [
|
||||
{
|
||||
matcher: "/store/*",
|
||||
middlewares: [
|
||||
urlencoded({ extended: true }),
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
Note that the `urlencoded` middleware imported from the [body-parser package](https://www.npmjs.com/package/body-parser) attaches the parsed data to the `MedusaRequest` object's `body` property as well.
|
||||
|
||||
---
|
||||
|
||||
## Protected API Routes
|
||||
|
||||
Protected API routes are routes that should only be accessible by logged-in customers or users.
|
||||
|
||||
### Protect Store API Routes
|
||||
|
||||
By default, API routes prefixed by `/store` don't require customer authentication to access the API route. However, you can still access the logged-in customer's ID in the API Route method handler using the `MedusaRequest` object's `user.customer_id`, which will be `undefined` if the customer isn't logged in.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import { CustomerService } from "@medusajs/medusa"
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const id = req.user.customer_id
|
||||
|
||||
if (!id) {
|
||||
// TODO handle not logged in
|
||||
// customers based on the custom
|
||||
// API route's functionality
|
||||
}
|
||||
|
||||
const customerService = req.scope.resolve<CustomerService>(
|
||||
"customerService"
|
||||
)
|
||||
|
||||
const customer = await customerService.retrieve(id)
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
API Routes prefixed by `/store/me`, on the other hand, require customer authentication to access the API Route. You can access the logged-in customer's ID in the API Route method handler using the `MedusaRequest` object's `user.customer_id`.
|
||||
|
||||
If you want to disable authentication requirement on your custom API Route prefixed with `/store/me`, export an `AUTHENTICATE` variable in the route file with its value set to `false`. For example:
|
||||
|
||||
```ts title=src/api/store/me/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
res.json({
|
||||
message: "Hello",
|
||||
})
|
||||
}
|
||||
|
||||
export const AUTHENTICATE = false
|
||||
```
|
||||
|
||||
:::note
|
||||
|
||||
This disables authentication requirement on all API Route methods defined in the same file.
|
||||
|
||||
:::
|
||||
|
||||
### Protect Admin API Routes
|
||||
|
||||
By default, all API Routes prefixed by `/admin` require admin user authentication to access the API Route. You can access the logged-in user's ID in the API Route method handler using the `MedusaRequest` object's `user.userId`.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/admin/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
UserService,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const id = req.user.userId
|
||||
|
||||
const userService = req.scope.resolve<UserService>(
|
||||
"userService"
|
||||
)
|
||||
|
||||
const user = await userService.retrieve(id)
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
To disable authentication requirement on an admin API Route, export an `AUTHENTICATE` variable in your route file with its value set to `false`.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/admin/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
res.json({
|
||||
message: "Hello",
|
||||
})
|
||||
}
|
||||
|
||||
export const AUTHENTICATE = false
|
||||
```
|
||||
|
||||
:::note
|
||||
|
||||
This disables authentication requirement on all API Route methods defined in the same file.
|
||||
|
||||
:::
|
||||
|
||||
### Protect Other API Routes
|
||||
|
||||
To protect API routes that aren't prefixed with `/store` or `/admin`, you can use one of the following middlewares exported by `@medusajs/medusa` for authenticating customers or users:
|
||||
|
||||
- `authenticate`: this middleware ensures that only authenticated admin users can access an API Route. You can access the user's ID in the API Route method handler using the `MedusaRequest` object's `user.userId`.
|
||||
- `authenticateCustomer`: this middleware doesn't require a customer to be authenticated, but if a customer is logged in, it attaches their ID to the `MedusaRequest` object's `user.customer_id`.
|
||||
- `requireCustomerAuthentication`: this middleware ensures that only authenticated customers can access an API Route. You can access the customer's ID in the API Route method handler using the `MedusaRequest` object's `user.customer_id`.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/middlewares.ts
|
||||
import {
|
||||
authenticate,
|
||||
requireCustomerAuthentication,
|
||||
type MiddlewaresConfig,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const config: MiddlewaresConfig = {
|
||||
routes: [
|
||||
{
|
||||
matcher: "/custom/admin*",
|
||||
middlewares: [authenticate()],
|
||||
},
|
||||
{
|
||||
matcher: "/custom/customer*",
|
||||
middlewares: [requireCustomerAuthentication()],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Retrieve Medusa Config
|
||||
|
||||
You can access the configurations exported in `medusa-config.js`, including your custom configurations, by resolving the `configModule` resource using [dependency injection](../fundamentals/dependency-injection.md).
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import { ConfigModule } from "@medusajs/medusa"
|
||||
|
||||
// This is only helpful if you're
|
||||
// accessing custom configurations
|
||||
// otherwise it's fine to just use `ConfigModule`
|
||||
type MyConfigModule = ConfigModule & {
|
||||
projectConfig: {
|
||||
custom_config?: string
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const configModule = req.scope.resolve<MyConfigModule>(
|
||||
"configModule"
|
||||
)
|
||||
res.json({
|
||||
message: configModule.projectConfig.custom_config,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Handle Errors
|
||||
|
||||
Medusa provides an `errorHandler` middleware that you can use on your custom API Routes so that your error handling is consistent with the Medusa backend. You can also create custom [middlewares](./add-middleware.mdx) to handle errors.
|
||||
|
||||
To handle errors using Medusa's middlewares, first, import the `errorHandler` middleware from `@medusajs/medusa` and apply it on your routes.
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=src/api/middlewares.ts
|
||||
import {
|
||||
errorHandler,
|
||||
type MiddlewaresConfig,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const config: MiddlewaresConfig = {
|
||||
routes: [
|
||||
{
|
||||
matcher: "/store/custom*",
|
||||
middlewares: [errorHandler()],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
Make sure it's applied after all other middlewares.
|
||||
|
||||
Then, wrap the method handler function of every API route method with the `wrapHandler` function imported from `@medusajs/medusa`. For example:
|
||||
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
wrapHandler,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const GET = wrapHandler(async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
res.json({
|
||||
message: "[GET] Hello world!",
|
||||
})
|
||||
})
|
||||
|
||||
export const POST = wrapHandler(async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
res.json({
|
||||
message: "[POST] Hello world!",
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Now all errors thrown in your custom API Routes, or in resources you use within your API Route such as services, are caught and returned to the user.
|
||||
|
||||
### Using MedusaError
|
||||
|
||||
If you throw errors like this:
|
||||
|
||||
```ts
|
||||
throw new Error ("Post was not found")
|
||||
```
|
||||
|
||||
The API Route returns the following object error in the response:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "unknown_error",
|
||||
"type": "unknown_error",
|
||||
"message": "An unknown error occurred."
|
||||
}
|
||||
```
|
||||
|
||||
To ensure your error message is relayed in the response, it's recommended to use `MedusaError` imported from `@medusajs/utils` as the thrown error instead.
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
import { MedusaError } from "@medusajs/utils"
|
||||
|
||||
// ...
|
||||
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.NOT_FOUND,
|
||||
"Post was not found"
|
||||
)
|
||||
```
|
||||
|
||||
The constructor of `MedusaError` accepts the following parameters:
|
||||
|
||||
1. The first parameter is the error's type. You can use one of the predefined errors under `MedusaError.Types`, such as `MedusaError.Types.NOT_FOUND` which sets the response status code to `404` automatically.
|
||||
2. The second parameter is the message of the error.
|
||||
3. The third parameter is an optional code, which is a string, that's returned in the error object.
|
||||
|
||||
After using `MedusaError`, the returned error in the response provides a clearer message:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "not_found",
|
||||
"message": "Post was not found"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Use Other Resources
|
||||
|
||||
Resources, such as services, that are registered in the [dependency container](../fundamentals/dependency-injection.md) can be retrieved in an API Route's handler method using the `MedusaRequest` object's `scope.resolve` method.
|
||||
|
||||
The `scope` method accepts as a parameter the resource's registration name in the [dependency container](../fundamentals/dependency-injection.md).
|
||||
|
||||
### Example: Retrieve Repository
|
||||
|
||||
:::tip
|
||||
|
||||
Posts are represented by a custom entity not covered in this guide. You can refer to the [entities](../entities/create.mdx#adding-relations) for more details on how to create a custom entity.
|
||||
|
||||
:::
|
||||
|
||||
```ts title=src/api/store/posts/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import {
|
||||
PostRepository,
|
||||
} from "../../../repositories/post"
|
||||
import { EntityManager } from "typeorm"
|
||||
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const postRepository =
|
||||
req.scope.resolve<PostRepository>("postRepository")
|
||||
const manager = req.scope.resolve<EntityManager>("manager")
|
||||
const postRepo = manager.withRepository(postRepository)
|
||||
|
||||
res.json({
|
||||
posts: await postRepo.find(),
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
Notice that to retrieve an instance of the repository, you need to retrieve first Typeorm's Entity Manager from the dependency container, then use its `withRepository` method.
|
||||
|
||||
### Example: Retrieve Service
|
||||
|
||||
:::note
|
||||
|
||||
`PostService` is a custom service that is not covered in this guide. You can refer to the [services](../services/create-service.mdx) documentation for more details on how to create a custom service, and find an [example of PostService](../services/create-service.mdx#example-services-with-crud-operations)
|
||||
|
||||
:::
|
||||
|
||||
```ts title=src/api/store/posts/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import { PostService } from "../../../services/post"
|
||||
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const postService: PostService = req.scope.resolve(
|
||||
"postService"
|
||||
)
|
||||
|
||||
res.json({
|
||||
posts: await postService.list(),
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ignored Files and Directories
|
||||
|
||||
Files and directories prefixed with `_` are ignored. This can be helpful if you want to implement API Route method handlers in different files, then reference them in your `route.ts` file.
|
||||
|
||||
For example:
|
||||
|
||||
<Tabs groupId="files" isCodeTabs={true}>
|
||||
<TabItem value="custom-route" label="src/api/custom/route.ts" default>
|
||||
|
||||
```ts
|
||||
import getProducts from "../_methods/get-products"
|
||||
|
||||
export const GET = getProducts
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="internal-method" label="src/api/_methods/get-product.ts">
|
||||
|
||||
```ts
|
||||
import {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
ProductService,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export default async function (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) {
|
||||
const productService = req.scope.resolve<ProductService>(
|
||||
"productService"
|
||||
)
|
||||
|
||||
const products = await productService.list({})
|
||||
|
||||
res.json({
|
||||
products,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
---
|
||||
|
||||
## Example: CRUD API Routes
|
||||
|
||||
This section provides an example of creating API Routes that perform Create, Read, Update, and Delete (CRUD) operations.
|
||||
|
||||
:::note
|
||||
|
||||
You can refer to the [Entities](../entities/create.mdx#adding-relations) and [Services](../services/create-service.mdx#example-services-with-crud-operations) documentation to learn how to create the custom entities and services used in this example.
|
||||
|
||||
:::
|
||||
|
||||
<Tabs groupId="files" isCodeTabs={true}>
|
||||
<TabItem value="posts-routes" label="src/api/admin/posts/route.ts" default>
|
||||
|
||||
```ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import { PostService } from "../../../services/post"
|
||||
|
||||
// list posts
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const postService: PostService = req.scope.resolve(
|
||||
"postService"
|
||||
)
|
||||
|
||||
res.json({
|
||||
posts: await postService.list(),
|
||||
})
|
||||
}
|
||||
|
||||
// create a post
|
||||
export const POST = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const postService: PostService = req.scope.resolve(
|
||||
"postService"
|
||||
)
|
||||
|
||||
// basic validation of request body
|
||||
if (!req.body.title || !req.body.author_id) {
|
||||
throw new Error("`title` and `author_id` are required.")
|
||||
}
|
||||
|
||||
const post = await postService.create(req.body)
|
||||
|
||||
res.json({
|
||||
post,
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="posts-id-routes" label="src/api/admin/posts/[id]/route.ts">
|
||||
|
||||
```ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import { PostService } from "../../../services/post"
|
||||
|
||||
// retrieve a post by its ID
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const postService: PostService = req.scope.resolve(
|
||||
"postService"
|
||||
)
|
||||
|
||||
const post = await postService.retrieve(req.params.id)
|
||||
|
||||
res.json({
|
||||
post,
|
||||
})
|
||||
}
|
||||
|
||||
// update a post by its ID
|
||||
export const POST = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const postService: PostService = req.scope.resolve(
|
||||
"postService"
|
||||
)
|
||||
|
||||
// basic validation of request body
|
||||
if (req.body.id) {
|
||||
throw new Error("Can't update post ID")
|
||||
}
|
||||
|
||||
const post = await postService.update(
|
||||
req.params.id,
|
||||
req.body
|
||||
)
|
||||
|
||||
res.json({
|
||||
post,
|
||||
})
|
||||
}
|
||||
|
||||
// delete a post by its ID
|
||||
export const DELETE = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const postService: PostService = req.scope.resolve(
|
||||
"postService"
|
||||
)
|
||||
|
||||
await postService.delete(req.params.id)
|
||||
|
||||
res.status(200).end()
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Storefront API Reference](https://docs.medusajs.com/api/store)
|
||||
- [Admin API Reference](https://docs.medusajs.com/api/admin)
|
||||
@@ -0,0 +1,171 @@
|
||||
---
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
import Troubleshooting from '@site/src/components/Troubleshooting'
|
||||
import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md'
|
||||
import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md'
|
||||
|
||||
# Example: Access Logged-In User
|
||||
|
||||
This document gives an example of how you can use middlewares to register the logged-in user in the dependency container of your commerce application. You can then access the logged-in user in other resources, such as services.
|
||||
|
||||
:::tip
|
||||
|
||||
You can apply the same steps if you want to register the current customer.
|
||||
|
||||
:::
|
||||
|
||||
Learn more about [middlewares in its guide](./add-middleware.mdx).
|
||||
|
||||
## Step 1: Create the Middleware
|
||||
|
||||
Create the file `src/api/middlewares.ts` with the following content:
|
||||
|
||||
```ts title=src/api/middlewares.ts
|
||||
import type {
|
||||
MiddlewaresConfig,
|
||||
User,
|
||||
UserService,
|
||||
} from "@medusajs/medusa"
|
||||
import type {
|
||||
MedusaNextFunction,
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
const registerLoggedInUser = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse,
|
||||
next: MedusaNextFunction
|
||||
) => {
|
||||
let loggedInUser: User | null = null
|
||||
|
||||
if (req.user && req.user.userId) {
|
||||
const userService =
|
||||
req.scope.resolve("userService") as UserService
|
||||
loggedInUser = await userService.retrieve(req.user.userId)
|
||||
}
|
||||
|
||||
req.scope.register({
|
||||
loggedInUser: {
|
||||
resolve: () => loggedInUser,
|
||||
},
|
||||
})
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
export const config: MiddlewaresConfig = {
|
||||
routes: [
|
||||
{
|
||||
matcher: "/admin/products",
|
||||
middlewares: [registerLoggedInUser],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
This creates a `registerLoggedInUser` middleware that handles registering the logged-in user in the dependency container.
|
||||
|
||||
It then applies this middleware on the `/admin/products` API Route. You can change that to be the route of any other API Route or a pattern that matches multiple routes.
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Use in a Service
|
||||
|
||||
Access the logged-in user resource in the constructor of a service:
|
||||
|
||||
<!-- eslint-disable prefer-rest-params -->
|
||||
|
||||
```ts
|
||||
import { Lifetime } from "awilix"
|
||||
import {
|
||||
TransactionBaseService,
|
||||
User,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
class HelloService extends TransactionBaseService {
|
||||
|
||||
protected readonly loggedInUser_: User | null
|
||||
|
||||
constructor(container, options) {
|
||||
super(...arguments)
|
||||
|
||||
try {
|
||||
this.loggedInUser_ = container.loggedInUser
|
||||
} catch (e) {
|
||||
// avoid errors when backend first runs
|
||||
}
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
export default HelloService
|
||||
```
|
||||
|
||||
If you're accessing it in an extended core service, it’s important to change the lifetime of the service to `Lifetime.SCOPED`. For example:
|
||||
|
||||
<!-- eslint-disable prefer-rest-params -->
|
||||
|
||||
```ts
|
||||
import { Lifetime } from "awilix"
|
||||
import {
|
||||
ProductService as MedusaProductService,
|
||||
User,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
// extend core product service
|
||||
class ProductService extends MedusaProductService {
|
||||
// The default life time for a core service is SINGLETON
|
||||
static LIFE_TIME = Lifetime.SCOPED
|
||||
|
||||
protected readonly loggedInUser_: User | null
|
||||
|
||||
constructor(container, options) {
|
||||
super(...arguments)
|
||||
|
||||
this.loggedInUser_ = container.loggedInUser
|
||||
}
|
||||
}
|
||||
|
||||
export default ProductService
|
||||
```
|
||||
|
||||
You can learn more about the importance of changing the service lifetime in the [Middlewares documentation](./add-middleware.mdx#note-about-services-lifetime).
|
||||
|
||||
---
|
||||
|
||||
## Step 3: Test it Out
|
||||
|
||||
To test out your implementation, run the following command in the root directory of the Medusa backend to transpile your changes:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
```
|
||||
|
||||
Then, run your backend with the following command:
|
||||
|
||||
```bash npm2yarn
|
||||
npx medusa develop
|
||||
```
|
||||
|
||||
If you try accessing the API Routes you added the middleware to, you should see your implementation working as expected.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<Troubleshooting
|
||||
sections={[
|
||||
{
|
||||
title: 'AwilixResolutionError: Could Not Resolve X',
|
||||
content: <ServiceLifetimeSection />
|
||||
},
|
||||
{
|
||||
title: 'AwilixResolutionError: Could Not Resolve X (Custom Registration)',
|
||||
content: <CustomRegistrationSection />
|
||||
}
|
||||
]}
|
||||
/>
|
||||
+9
-10
@@ -1,21 +1,20 @@
|
||||
---
|
||||
description: 'Learn how to extend a validator. This is useful when you want to pass additional data to endpoints in the Medusa core.'
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
# How to Extend an Endpoint Validator
|
||||
# How to Extend an API Route Validator
|
||||
|
||||
In this guide, you'll learn how to extend an endpoint validator from the Medusa core.
|
||||
In this guide, you'll learn how to extend an API Route validator from the Medusa core.
|
||||
|
||||
## Overview
|
||||
|
||||
Request fields passed to endpoints that are defined in the Medusa core are validated to ensure that only expected fields are passed, and the passed fields are of correct types.
|
||||
Request fields passed to API Routes defined in the Medusa core are validated to ensure that only expected fields are passed, and the passed fields are of correct types.
|
||||
|
||||
In some scenarios, you may need to allow passing custom fields into an existing endpoint. If a custom field is passed to an endpoint in the core, the endpoint returns an error in the response.
|
||||
In some scenarios, you may need to allow passing custom fields into an existing API Route. If a custom field is passed to an API Route in the core, the API Route returns an error in the response.
|
||||
|
||||
To allow passing custom fields into core endpoints, you must extend Validators. Validators are classes that are used by the core to validate the request parameters to an endpoint.
|
||||
To allow passing custom fields into core API Routes, you must extend Validators. Validators are classes that are used by the core to validate the request parameters to an API Route.
|
||||
|
||||
This guide explains how to extend a validator to allow passing custom fields to an endpoint. You'll be extending the validator of the admin API Create Product endpoint as an example.
|
||||
This guide explains how to extend a validator to allow passing custom fields to an API Route. You'll be extending the validator of the admin API Create Product route as an example.
|
||||
|
||||
---
|
||||
|
||||
@@ -59,13 +58,13 @@ registerOverriddenValidators(AdminPostProductsReq)
|
||||
In this code snippet you:
|
||||
|
||||
1. Import the `registerOverriddenValidators` function from the `@medusajs/medusa` package. This utility function allows you to extend validators in the core.
|
||||
2. Import the `AdminPostProductsReq` class from `@medusajs/medusa` as `MedusaAdminPostProductsReq` since this guide extends the Create Product endpoint validator. If you're extending a different validator, make sure to import it instead.
|
||||
2. Import the `AdminPostProductsReq` class from `@medusajs/medusa` as `MedusaAdminPostProductsReq` since this guide extends the Create Product API Route validator. If you're extending a different validator, make sure to import it instead.
|
||||
3. Create a class `AdminPostProductsReq` that extends `MedusaAdminPostProductsReq` and adds a new field `custom_field`. Notice that the name of the class must be the same name of the validator defined in the core. `custom_field` has the type `string`. You can change the type or name of the field, or add more fields.
|
||||
4. Call `registerOverriddenValidators` passing it the `AdminPostProductsReq` class you created. This will override the validator defined in the core to include the new field `custom_field` among the existing fields defined in the core.
|
||||
|
||||
:::tip
|
||||
|
||||
Validators are defined in the same file as the endpoint. To find the validator you need to override, find the endpoint file under `@medusajs/medusa/dist/api/routes` and import the validator in that file.
|
||||
Validators are defined in the same file as the API Route. To find the validator you need to override, find the API Route file under `@medusajs/medusa/dist/api/routes` and import the validator in that file.
|
||||
|
||||
:::
|
||||
|
||||
@@ -80,4 +79,4 @@ npm run build
|
||||
npx medusa develop
|
||||
```
|
||||
|
||||
Then, send a request to the endpoint you extended passing it your custom fields. To test out the example in this guide, send an [authenticated request](https://docs.medusajs.com/api/admin#authentication) to the [Create Product endpoint](https://docs.medusajs.com/api/admin#products_postproducts) and pass it the `custom_field` body parameter. The request should execute with no errors.
|
||||
Then, send a request to the API Route you extended passing it your custom fields. To test out the example in this guide, send an [authenticated request](https://docs.medusajs.com/api/admin#authentication) to the [Create Product API Route](https://docs.medusajs.com/api/admin#products_postproducts) and pass it the `custom_field` body parameter. The request should execute with no errors.
|
||||
@@ -0,0 +1,68 @@
|
||||
import DocCardList from '@theme/DocCardList';
|
||||
import Icons from '@theme/Icon';
|
||||
|
||||
# API Routes
|
||||
|
||||
In this document, you’ll learn what API Routes are in Medusa.
|
||||
|
||||
## Introduction
|
||||
|
||||
The Medusa Backend is a Node.js headless server. It exposes commerce functionalities implemented by Medusa's [commerce module](../../modules/overview.mdx) through REST APIs that external or frontend applications can access to process or retrieve data.
|
||||
|
||||
The backend exposes two types of API routes: Store APIs and Admin APIs. The Store APIs are typically accessed from the storefront. For example, you can use the Store APIs to show customers available products or implement a cart and checkout flow.
|
||||
|
||||
The Admin APIs are typically accessed from an admin dashboard. For example, you can use the Admin APIs to allow admins to manage the store’s data such as products, orders, and so on.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: 'https://docs.medusajs.com/api/store',
|
||||
label: 'Store APIs',
|
||||
customProps: {
|
||||
icon: Icons['server-solid'],
|
||||
description: 'Check out available Store REST APIs.'
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: 'https://docs.medusajs.com/api/admin',
|
||||
label: 'Admin APIs',
|
||||
customProps: {
|
||||
icon: Icons['server-solid'],
|
||||
description: 'Check out available Admin REST APIs.'
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Custom Development
|
||||
|
||||
Aside from using the Medusa backend's API routes, developers can create their own API routes either directly in the Medusa Backend or in a plugin.
|
||||
|
||||
:::tip
|
||||
|
||||
As the core Medusa package is completely customizable, developers can also extend the functionality even further to implement GraphQL routes.
|
||||
|
||||
:::
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/api-routes/create',
|
||||
label: 'Create an API Route',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to create an API Route in Medusa.'
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/api-routes/add-middleware',
|
||||
label: 'Add a Middleware',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to add a middleware in Medusa.'
|
||||
}
|
||||
},
|
||||
]} />
|
||||
@@ -52,9 +52,9 @@ This section includes all configurations that belong to the `projectConfig` prop
|
||||
|
||||
### admin_cors and store_cors
|
||||
|
||||
The Medusa backend’s endpoints are protected by Cross-Origin Resource Sharing (CORS). So, only allowed URLs or URLs matching a specified pattern can send requests to the backend’s endpoints.
|
||||
The Medusa backend’s API Routes are protected by Cross-Origin Resource Sharing (CORS). So, only allowed URLs or URLs matching a specified pattern can send requests to the backend’s API Routes.
|
||||
|
||||
`admin_cors` is used to specify the accepted URLs or patterns for admin endpoints, and `store_cors` is used to specify the accepted URLs or patterns for store endpoints.
|
||||
`admin_cors` is used to specify the accepted URLs or patterns for admin API Routes, and `store_cors` is used to specify the accepted URLs or patterns for store API Routes.
|
||||
|
||||
For both the `admin_cors` and `store_cors`, the value is expected to be a string. This string can be a comma-separated list of accepted origins. Every origin in that list can be of the following types:
|
||||
|
||||
@@ -129,7 +129,7 @@ Its value is an object that has the following properties:
|
||||
- `memLevel`: A `number` value that specifies how much memory should be allocated to the internal compression state. It's an integer in the range of 1 (minimum level) and 9 (maximum level). The default value is `8`.
|
||||
- `threshold`: A `number` or a `string` value in bytes that specifies the minimum response body size that compression is applied on. This is the number of bytes or any string accepted by the bytes module. The default value is `1024`.
|
||||
|
||||
If you enable HTTP compression and you want to disable it for specific endpoints, you can pass in the request header `"x-no-compression": true`.
|
||||
If you enable HTTP compression and you want to disable it for specific API Routes, you can pass in the request header `"x-no-compression": true`.
|
||||
|
||||
```js title=medusa-config.js
|
||||
module.exports = {
|
||||
|
||||
@@ -136,9 +136,9 @@ This directory holds all Medusa admin customizations. The main subdirectories of
|
||||
|
||||
### api
|
||||
|
||||
This directory holds all custom endpoints. You can create as many subdirectories and files that hold endpoint definitions, but only endpoints exported by the `index.ts` file are registered in the Medusa backend.
|
||||
This directory holds all custom API Routes, which are defined in `route.ts` or `route.js` files. These files can be created in sub-directories of the `api` directory based on the API Route's path.
|
||||
|
||||
**Read more:** [Endpoints](../endpoints/overview.mdx)
|
||||
**Read more:** [API Routes](../api-routes/overview.mdx)
|
||||
|
||||
### loaders
|
||||
|
||||
|
||||
@@ -288,7 +288,7 @@ If you follow along with the JS Client code snippets, make sure to [install and
|
||||
|
||||
### Create Batch Job
|
||||
|
||||
The first step is to create a batch job using the [Create Batch Job endpoint](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs). In the body of the request, you must set the `type` to the value of `batchType` in the batch job strategy you created.
|
||||
The first step is to create a batch job using the [Create Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs). In the body of the request, you must set the `type` to the value of `batchType` in the batch job strategy you created.
|
||||
|
||||
For example, this creates a batch job of the type `publish-products`:
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ npm run build
|
||||
|
||||
Since you didn’t create a new batch job type and overwrote the functionality of the strategy, you can test out your functionality using the [same steps used with the default strategy](./create.mdx#test-your-batch-job-strategy).
|
||||
|
||||
Specifically, since you create batch jobs using the [Create Batch Job](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs) endpoint which accepts the batch job type as a body parameter, you just need to send the same type you used for this field. In the example of this documentation, the `type` would be `product-import`.
|
||||
Specifically, since you create batch jobs using the [Create Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs) which accepts the batch job type as a body parameter, you just need to send the same type you used for this field. In the example of this documentation, the `type` would be `product-import`.
|
||||
|
||||
If you overwrote the import functionality, you can follow [these steps to learn how to import products using the Admin APIs](../../modules/products/admin/import-products.mdx).
|
||||
|
||||
|
||||
@@ -49,15 +49,15 @@ When you create a batch job strategy, the `batchType` class property indicates t
|
||||
|
||||
A batch job’s flow from creation to completion is:
|
||||
|
||||
1. A batch job is created using the [Create Batch Job API endpoint](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs).
|
||||
1. A batch job is created using the [Create Batch Job API route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobs).
|
||||
2. Once the batch job is created, the batch job’s status is changed to `created` and the `batch.created` event is triggered by the `BatchJobService`.
|
||||
3. The `BatchJobSubscriber` handles the `created` event. It resolves the batch job strategy based on the `type` of the batch job, then uses it to pre-process the batch job. After this, the batch job’s status is changed to `pre_processed`. Only when the batch job has the status `pre_processed` can be confirmed.
|
||||
4. If `dry_run` is not set in the Create Batch Job request in step one or if it is set to `false`, the batch job will automatically be confirmed after processing. Otherwise, if `dry_run` is set to `true`, the batch job can be confirmed using the [Confirm Batch Job API](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobsbatchjobconfirmprocessing) endpoint.
|
||||
4. If `dry_run` is not set in the Create Batch Job request in step one or if it is set to `false`, the batch job will automatically be confirmed after processing. Otherwise, if `dry_run` is set to `true`, the batch job can be confirmed using the [Confirm Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_postbatchjobsbatchjobconfirmprocessing).
|
||||
5. Once the batch job is confirmed, the batch job’s status is changed to `confirmed` and the `batch.confirmed` event is triggered by the `BatchJobService`.
|
||||
6. The `BatchJobSubscriber` handles the `confirmed` event. It resolves the batch job strategy, then uses it to process the batch job.
|
||||
7. Once the batch job is processed successfully, the batch job has the status `completed`.
|
||||
|
||||
You can track the progress of the batch job at any point using the [Retrieve Batch Job](https://docs.medusajs.com/api/admin#batch-jobs_getbatchjobsbatchjob) endpoint.
|
||||
You can track the progress of the batch job at any point using the [Retrieve Batch Job API Route](https://docs.medusajs.com/api/admin#batch-jobs_getbatchjobsbatchjob).
|
||||
|
||||
:::info
|
||||
|
||||
|
||||
@@ -1,220 +0,0 @@
|
||||
---
|
||||
description: 'In this document, you’ll see an example of how you can use middlewares and endpoints to register the logged-in user in the dependency container of your commerce application.'
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
import Troubleshooting from '@site/src/components/Troubleshooting'
|
||||
import ServiceLifetimeSection from '../../troubleshooting/awilix-resolution-error/_service-lifetime.md'
|
||||
import CustomRegistrationSection from '../../troubleshooting/awilix-resolution-error/_custom-registration.md'
|
||||
|
||||
# Example: Access Logged-In User
|
||||
|
||||
In this document, you’ll see an example of how you can use middlewares and endpoints to register the logged-in user in the dependency container of your commerce application. You can then access the logged-in user in other resources, such as services.
|
||||
|
||||
This guide showcases how to register the logged-in admin user, but you can apply the same steps if you want to register the current customer.
|
||||
|
||||
This documentation does not explain the basics of [middlewares](./add-middleware.mdx) and [endpoints](./create.mdx). You can refer to their respective guides for more details about each.
|
||||
|
||||
## Step 1: Create the Middleware
|
||||
|
||||
Create the file `src/api/middlewares/logged-in-user.ts` with the following content:
|
||||
|
||||
```ts title=src/api/middlewares/logged-in-user.ts
|
||||
import { User, UserService } from "@medusajs/medusa"
|
||||
|
||||
export async function registerLoggedInUser(req, res, next) {
|
||||
let loggedInUser: User | null = null
|
||||
|
||||
if (req.user && req.user.userId) {
|
||||
const userService =
|
||||
req.scope.resolve("userService") as UserService
|
||||
loggedInUser = await userService.retrieve(req.user.userId)
|
||||
}
|
||||
|
||||
req.scope.register({
|
||||
loggedInUser: {
|
||||
resolve: () => loggedInUser,
|
||||
},
|
||||
})
|
||||
|
||||
next()
|
||||
}
|
||||
```
|
||||
|
||||
This retrieves the ID of the current user to retrieve an instance of it, then registers it in the scope under the name `loggedInUser`.
|
||||
|
||||
---
|
||||
|
||||
## Step 2: Apply Middleware on Endpoint
|
||||
|
||||
If you don't have the `cors` package installed, make sure to install it first:
|
||||
|
||||
```bash npm2yarn
|
||||
npm install cors
|
||||
```
|
||||
|
||||
Then, create the file `src/api/routes/create-product.ts` with the following content:
|
||||
|
||||
```ts title=src/api/routes/create-product.ts
|
||||
import cors from "cors"
|
||||
import { Router } from "express"
|
||||
import {
|
||||
registerLoggedInUser,
|
||||
} from "../middlewares/logged-in-user"
|
||||
import
|
||||
authenticate
|
||||
from "@medusajs/medusa/dist/api/middlewares/authenticate"
|
||||
|
||||
const router = Router()
|
||||
|
||||
export default function (adminCorsOptions) {
|
||||
// This router will be applied before the core routes.
|
||||
// Therefore, the middleware will be executed
|
||||
// before the create product handler is hit
|
||||
router.use(
|
||||
"/admin/products",
|
||||
cors(adminCorsOptions),
|
||||
authenticate(),
|
||||
registerLoggedInUser
|
||||
)
|
||||
return router
|
||||
}
|
||||
```
|
||||
|
||||
In the example above, the middleware is applied on the `/admin/products` core endpoint. However, you can apply it on any other endpoint. You can also apply it to custom endpoints.
|
||||
|
||||
For endpoints that require Cross-Origin Resource Origin (CORS) options, such as core endpoints, you must pass the CORS options to the middleware as well since it will be executed before the underlying endpoint.
|
||||
|
||||
:::tip
|
||||
|
||||
In the above code snippet, the `authenticate` middleware imported from `@medusajs/medusa` is used to ensure that the user is logged in first. If you're implementing this for middleware to register the logged-in customer, make sure to use the [customer's authenticate middleware](./create.mdx#protect-store-routes).
|
||||
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
## Step 3: Register Endpoint in the API
|
||||
|
||||
Create the file `src/api/index.ts` with the following content:
|
||||
|
||||
```ts title=src/api/index.ts
|
||||
import configLoader from "@medusajs/medusa/dist/loaders/config"
|
||||
import createProductRouter from "./routes/create-product"
|
||||
|
||||
export default function (rootDirectory: string) {
|
||||
const config = configLoader(rootDirectory)
|
||||
|
||||
const adminCors = {
|
||||
origin: config.projectConfig.admin_cors.split(","),
|
||||
credentials: true,
|
||||
}
|
||||
|
||||
const productRouters = [
|
||||
createProductRouter(adminCors),
|
||||
]
|
||||
|
||||
return [...productRouters]
|
||||
}
|
||||
```
|
||||
|
||||
This exports an array of endpoints, one of them being the product endpoint that you applied the middleware on in the second step. You can export more endpoints as well.
|
||||
|
||||
---
|
||||
|
||||
## Step 4: Use in a Service
|
||||
|
||||
You can now access the logged-in user in a service. For example, to access it in a custom service:
|
||||
|
||||
<!-- eslint-disable prefer-rest-params -->
|
||||
|
||||
```ts
|
||||
import { Lifetime } from "awilix"
|
||||
import {
|
||||
TransactionBaseService,
|
||||
User,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
class HelloService extends TransactionBaseService {
|
||||
|
||||
protected readonly loggedInUser_: User | null
|
||||
|
||||
constructor(container, options) {
|
||||
super(...arguments)
|
||||
|
||||
try {
|
||||
this.loggedInUser_ = container.loggedInUser
|
||||
} catch (e) {
|
||||
// avoid errors when backend first runs
|
||||
}
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
export default HelloService
|
||||
```
|
||||
|
||||
If you're accessing it in an extended core service, it’s important to change the lifetime of the service to `Lifetime.SCOPED`. For example:
|
||||
|
||||
<!-- eslint-disable prefer-rest-params -->
|
||||
|
||||
```ts
|
||||
import { Lifetime } from "awilix"
|
||||
import {
|
||||
ProductService as MedusaProductService,
|
||||
User,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
// extend core product service
|
||||
class ProductService extends MedusaProductService {
|
||||
// The default life time for a core service is SINGLETON
|
||||
static LIFE_TIME = Lifetime.SCOPED
|
||||
|
||||
protected readonly loggedInUser_: User | null
|
||||
|
||||
constructor(container, options) {
|
||||
super(...arguments)
|
||||
|
||||
this.loggedInUser_ = container.loggedInUser
|
||||
}
|
||||
}
|
||||
|
||||
export default ProductService
|
||||
```
|
||||
|
||||
You can learn more about the importance of changing the service lifetime in the [Middlewares documentation](./add-middleware.mdx#note-about-services-lifetime).
|
||||
|
||||
---
|
||||
|
||||
## Step 5: Test it Out
|
||||
|
||||
To test out your implementation, run the following command in the root directory of the Medusa backend to transpile your changes:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
```
|
||||
|
||||
Then, run your backend with the following command:
|
||||
|
||||
```bash npm2yarn
|
||||
npx medusa develop
|
||||
```
|
||||
|
||||
If you try accessing the endpoints you added the middleware to, you should see your implementation working as expected.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<Troubleshooting
|
||||
sections={[
|
||||
{
|
||||
title: 'AwilixResolutionError: Could Not Resolve X',
|
||||
content: <ServiceLifetimeSection />
|
||||
},
|
||||
{
|
||||
title: 'AwilixResolutionError: Could Not Resolve X (Custom Registration)',
|
||||
content: <CustomRegistrationSection />
|
||||
}
|
||||
]}
|
||||
/>
|
||||
@@ -1,76 +0,0 @@
|
||||
---
|
||||
description: "Learn what endpoints are in Medusa. Endpoints are REST APIs that allow a frontend or external system to interact with the Backend."
|
||||
---
|
||||
|
||||
import DocCardList from '@theme/DocCardList';
|
||||
import Icons from '@theme/Icon';
|
||||
|
||||
# Endpoints
|
||||
|
||||
In this document, you’ll learn what endpoints are in Medusa.
|
||||
|
||||
## Introduction
|
||||
|
||||
The Medusa Backend is a web server built on top of [Express](https://expressjs.com/), a Node.js web framework. This provides developers with all the functionalities available within Express during development. One of those are endpoints.
|
||||
|
||||
Endpoints are REST APIs that allow a frontend or an external system to interact with the Medusa Backend to retrieve and process data, or perform business logic. Endpoints are [Express routes](https://expressjs.com/en/starter/basic-routing.html).
|
||||
|
||||
Each [commerce module](../../modules/overview.mdx) contains a set of endpoints specific to the functionalities that it provides. Since the core package that powers the Medusa Backend acts as an orchestrator of commerce modules and exposes their endpoints, the endpoints of each of these commerce modules are available within the Medusa Backend.
|
||||
|
||||
The commerce modules provide two types of endpoints: Store APIs and Admin APIs. The Store APIs are typically accessed from the storefront. For example, you can use the Store APIs to show customers available products or implement a cart and checkout flow.
|
||||
|
||||
The Admin APIs are typically accessed from an admin dashboard. For example, you can use the Admin APIs to allow admins to manage the store’s data such as products, orders, and so on.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: 'https://docs.medusajs.com/api/store',
|
||||
label: 'Store APIs',
|
||||
customProps: {
|
||||
icon: Icons['server-solid'],
|
||||
description: 'Check out available Store REST APIs.'
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: 'https://docs.medusajs.com/api/admin',
|
||||
label: 'Admin APIs',
|
||||
customProps: {
|
||||
icon: Icons['server-solid'],
|
||||
description: 'Check out available Admin REST APIs.'
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Custom Development
|
||||
|
||||
Aside from using the endpoints that commerce modules, developers can create their own REST APIs either directly in the Medusa Backend, in a plugin, or in a custom commerce module.
|
||||
|
||||
:::tip
|
||||
|
||||
As the core Medusa package is completely customizable, developers can also extend the functionality even further to implement GraphQL endpoints.
|
||||
|
||||
:::
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/endpoints/create',
|
||||
label: 'Create an Endpoint',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to create an endpoint in Medusa.'
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/endpoints/add-middleware',
|
||||
label: 'Add a Middleware',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to add a middleware in Medusa.'
|
||||
}
|
||||
},
|
||||
]} />
|
||||
@@ -124,21 +124,21 @@ You can now use your extended entity throughout your commerce application.
|
||||
|
||||
---
|
||||
|
||||
## Access Custom Attributes and Relations in Core Endpoints
|
||||
## Access Custom Attributes and Relations in Core API Routes
|
||||
|
||||
### Request Parameters
|
||||
|
||||
In most cases, after you extend an entity to add new attributes, you'll likely need to pass these attributes to endpoints defined in the core. By default, this causes an error, as request parameters are validated to ensure only those that are defined are passed to the endpoint.
|
||||
In most cases, after you extend an entity to add new attributes, you'll likely need to pass these attributes to API Routes defined in the core. By default, this causes an error, as request parameters are validated to ensure only those that are defined are passed to the API Route.
|
||||
|
||||
To allow passing your custom attribute, you'll need to [extend the validator](../endpoints/extend-validator.md) of the endpoint.
|
||||
To allow passing your custom attribute, you'll need to [extend the validator](../api-routes/extend-validator.md) of the API Route.
|
||||
|
||||
### Response Fields
|
||||
|
||||
After you add custom attributes, you'll notice that these attributes aren't returned as part of the response fields of core endpoints. Core endpoints have a defined set of fields and relations that can be returned by default in requests.
|
||||
After you add custom attributes, you'll notice that these attributes aren't returned as part of the response fields of core API Routes. Core API Routes have a defined set of fields and relations that can be returned by default in requests.
|
||||
|
||||
To change that and ensure your custom attribute is returned in your request, you can extend the allowed fields of a set of endpoints in a loader file and add your attribute into them.
|
||||
To change that and ensure your custom attribute is returned in your request, you can extend the allowed fields of a set of API Routes in a loader file and add your attribute into them.
|
||||
|
||||
For example, if you added a custom attribute in the `Product` entity and you want to ensure it's returned in all the product's store endpoints (endpoints under the prefix `/store/products`), you can create a file under the `src/loaders` directory in your Medusa backend with the following content:
|
||||
For example, if you added a custom attribute in the `Product` entity and you want to ensure it's returned in all the product's store API Routes (API Routes under the prefix `/store/products`), you can create a file under the `src/loaders` directory in your Medusa backend with the following content:
|
||||
|
||||
```ts title=src/loaders/extend-product-fields.ts
|
||||
export default async function () {
|
||||
@@ -156,10 +156,10 @@ export default async function () {
|
||||
}
|
||||
```
|
||||
|
||||
In the code snippet above, you import `@medusajs/medusa/dist/api/routes/store/products/index`, which is where all the product's store endpoints are exported. In that file, there are the following defined variables:
|
||||
In the code snippet above, you import `@medusajs/medusa/dist/api/routes/store/products/index`, which is where all the product's store API Routes are exported. In that file, there are the following defined variables:
|
||||
|
||||
- `allowedStoreProductsFields`: The fields or attributes of a product that are allowed to be retrieved and returned in the product's store endpoints. This would allow you to pass your custom attribute in the `fields` request parameter of the product's store endpoints.
|
||||
- `defaultStoreProductsFields`: The fields or attributes of a product that are retrieved and returned by default in the product's store endpoints.
|
||||
- `allowedStoreProductsFields`: The fields or attributes of a product that are allowed to be retrieved and returned in the product's store API Routes. This would allow you to pass your custom attribute in the `fields` request parameter of the product's store API Routes.
|
||||
- `defaultStoreProductsFields`: The fields or attributes of a product that are retrieved and returned by default in the product's store API Routes.
|
||||
|
||||
You change the values of these variables and pass the name of your custom attribute. Make sure to change `customAttribute` to the name of your custom attribute.
|
||||
|
||||
@@ -171,10 +171,10 @@ Before you test out the above change, make sure to build your changes before you
|
||||
|
||||
You can also add custom relations by changing the following defined variables:
|
||||
|
||||
- `allowedStoreProductsRelations`: The relations of a product that are allowed to be retrieved and returned in the product's store endpoints. This would allow you to pass your custom relation in the `expand` request parameter of the product's store endpoints.
|
||||
- `defaultStoreProductsRelations`: The relations of a product that are retrieved and returned by default in the product's store endpoints.
|
||||
- `allowedStoreProductsRelations`: The relations of a product that are allowed to be retrieved and returned in the product's store API Routes. This would allow you to pass your custom relation in the `expand` request parameter of the product's store API Routes.
|
||||
- `defaultStoreProductsRelations`: The relations of a product that are retrieved and returned by default in the product's store API Routes.
|
||||
|
||||
If you want to apply this example for a different entity or set of endpoints, you would need to change the import path `@medusajs/medusa/dist/api/routes/store/products/index` to the path of the endpoints you're targeting. You also need to change `allowedStoreProductsFields` and `defaultStoreProductsFields` to the names of the variables in that file, and the same goes for relations. Typically, these names would be of the format `(allowed|default)(Store|Admin)(Entity)(Fields|Relation)`.
|
||||
If you want to apply this example for a different entity or set of API Routes, you would need to change the import path `@medusajs/medusa/dist/api/routes/store/products/index` to the path of the API Routes you're targeting. You also need to change `allowedStoreProductsFields` and `defaultStoreProductsFields` to the names of the variables in that file, and the same goes for relations. Typically, these names would be of the format `(allowed|default)(Store|Admin)(Entity)(Fields|Relation)`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -83,32 +83,35 @@ After that, you can add your custom methods to the repository. In the example ab
|
||||
|
||||
## Step 3: Use Your Extended Repository
|
||||
|
||||
You can now use your extended repository in other resources such as services or endpoints.
|
||||
You can now use your extended repository in other resources such as services or API Routes.
|
||||
|
||||
Here’s an example of using it in an endpoint:
|
||||
Here’s an example of using it in an API Route:
|
||||
|
||||
```ts
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import ProductRepository from "./path/to/product.ts"
|
||||
import EntityManager from "@medusajs/medusa"
|
||||
import { EntityManager } from "typeorm"
|
||||
|
||||
export default () => {
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
// ...
|
||||
|
||||
router.get("/custom-endpoint", (req, res) => {
|
||||
// ...
|
||||
const productRepository: typeof ProductRepository =
|
||||
req.scope.resolve(
|
||||
"productRepository"
|
||||
)
|
||||
const manager: EntityManager = req.scope.resolve("manager")
|
||||
const productRepo = manager.withRepository(
|
||||
productRepository
|
||||
)
|
||||
productRepo.customFunction()
|
||||
|
||||
const productRepository: typeof ProductRepository =
|
||||
req.scope.resolve(
|
||||
"productRepository"
|
||||
)
|
||||
const manager: EntityManager = req.scope.resolve("manager")
|
||||
const productRepo = manager.withRepository(
|
||||
productRepository
|
||||
)
|
||||
productRepo.customFunction()
|
||||
|
||||
// ...
|
||||
})
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -80,10 +80,10 @@ Developers can create custom entities in the Medusa backend, a plugin, or in a m
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/entities/create',
|
||||
label: 'Create an Endpoint',
|
||||
label: 'Create an API Route',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to create endpoints in Medusa.'
|
||||
description: 'Learn how to create API Routes in Medusa.'
|
||||
}
|
||||
},
|
||||
]} />
|
||||
@@ -39,27 +39,26 @@ class PostService extends TransactionBaseService {
|
||||
}
|
||||
```
|
||||
|
||||
Another example is retrieving the default repository of an entity in an endpoint:
|
||||
Another example is retrieving the default repository of an entity in an API Route:
|
||||
|
||||
```ts title=src/api/index.ts
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import { Post } from "../models/post"
|
||||
import { EntityManager } from "typeorm"
|
||||
|
||||
// ...
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const manager: EntityManager = req.scope.resolve("manager")
|
||||
const postRepo = manager.getRepository(Post)
|
||||
|
||||
export default () => {
|
||||
// ...
|
||||
|
||||
storeRouter.get("/posts", async (req, res) => {
|
||||
const manager: EntityManager = req.scope.resolve("manager")
|
||||
const postRepo = manager.getRepository(Post)
|
||||
|
||||
return res.json({
|
||||
posts: await postRepo.find(),
|
||||
})
|
||||
return res.json({
|
||||
posts: await postRepo.find(),
|
||||
})
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
@@ -105,35 +104,36 @@ A data source is Typeorm’s connection settings that allows you to connect to y
|
||||
|
||||
## Using Custom Repositories in Other Resources
|
||||
|
||||
### Endpoints
|
||||
### API Routes
|
||||
|
||||
To access a custom repository within an endpoint, use the `req.scope.resolve` method. For example:
|
||||
To access a custom repository within an API Route, use the `MedusaRequest` object's `scope.resolve` method.
|
||||
|
||||
```ts title=src/api/index.ts
|
||||
For example:
|
||||
|
||||
```ts title=src/store/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import { PostRepository } from "../repositories/post"
|
||||
import { EntityManager } from "typeorm"
|
||||
|
||||
// ...
|
||||
export const GET = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
const postRepository: typeof PostRepository =
|
||||
req.scope.resolve("postRepository")
|
||||
const manager: EntityManager = req.scope.resolve("manager")
|
||||
const postRepo = manager.withRepository(postRepository)
|
||||
|
||||
export default () => {
|
||||
// ...
|
||||
|
||||
storeRouter.get("/posts", async (req, res) => {
|
||||
const postRepository: typeof PostRepository =
|
||||
req.scope.resolve("postRepository")
|
||||
const manager: EntityManager = req.scope.resolve("manager")
|
||||
const postRepo = manager.withRepository(postRepository)
|
||||
|
||||
return res.json({
|
||||
posts: await postRepo.find(),
|
||||
})
|
||||
return res.json({
|
||||
posts: await postRepo.find(),
|
||||
})
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
You can learn more about endpoints [here](../endpoints/overview.mdx).
|
||||
You can learn more about API Route [here](../api-routes/overview.mdx).
|
||||
|
||||
### Services and Subscribers
|
||||
|
||||
@@ -336,4 +336,4 @@ You can later retrieve that entity by passing the `withDeleted` option to method
|
||||
const posts = await postRepository.find({
|
||||
withDeleted: true,
|
||||
})
|
||||
```
|
||||
```
|
||||
|
||||
@@ -2218,7 +2218,7 @@ Triggered when a product and data associated with it (options, variant orders, e
|
||||
|
||||
The entire product passed as an object. You can refer to the [Product entity](../../references/entities/classes/Product.md) for an idea of what fields to expect.
|
||||
|
||||
In one case, when the `/admin/products/{id}` endpoint is used to update the product, the payload is an object of the following format:
|
||||
In one case, when the `/admin/products/{id}` API Route is used to update the product, the payload is an object of the following format:
|
||||
|
||||
```js noReport noCopy
|
||||
{
|
||||
|
||||
@@ -13,7 +13,7 @@ In this document, you’ll learn what feature flags in Medusa.
|
||||
|
||||
Feature flags are used in Medusa to guard beta features that aren’t ready for live and production applications. This allows the Medusa team to keep publishing releases more frequently, while also working on necessary future features behind the scenes. To use these beta features, you must enable their feature flags.
|
||||
|
||||
If a feature is guarded by a flag, entities, migrations, endpoints, and other resources associated with that feature are guarded by that flag as well. So, these resources will only be available to use in Medusa if you have enabled the associated feature flag.
|
||||
If a feature is guarded by a flag, entities, migrations, API Routes, and other resources associated with that feature are guarded by that flag as well. So, these resources will only be available to use in Medusa if you have enabled the associated feature flag.
|
||||
|
||||
You can view a list of available feature flags that you can toggle in [the Beta Features documentation](../../beta.md).
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ You can learn more about migrations in this documentation.
|
||||
|
||||
Disabling feature flags follows the same process as enabling the feature flags. All you have to do is change the value in the environment variables or the backend configurations to `false`.
|
||||
|
||||
Once you disable a feature flag, all endpoints, entities, services, or other related classes and functionalities are disabled.
|
||||
Once you disable a feature flag, all API Routes, entities, services, or other related classes and functionalities are disabled.
|
||||
|
||||
### Revert Migrations
|
||||
|
||||
|
||||
@@ -438,7 +438,7 @@ Run your backend to test it out:
|
||||
npx medusa develop
|
||||
```
|
||||
|
||||
Then, try uploading a file, for example, using the [Upload File endpoint](https://docs.medusajs.com/api/admin#uploads_postuploads). The file should be uploaded based on the logic you’ve implemented.
|
||||
Then, try uploading a file, for example, using the [Upload File API Route](https://docs.medusajs.com/api/admin#uploads_postuploads). The file should be uploaded based on the logic you’ve implemented.
|
||||
|
||||
### (Optional) Accessing the File
|
||||
|
||||
@@ -452,15 +452,17 @@ Since the file is uploaded to a local directory `uploads`, you need to configure
|
||||
|
||||
To do that, create the file `src/api/index.ts` with the following content:
|
||||
|
||||
```ts
|
||||
```ts title=src/api/middlewares.ts
|
||||
import type { MiddlewaresConfig } from "@medusajs/medusa"
|
||||
import express from "express"
|
||||
|
||||
export default () => {
|
||||
const app = express.Router()
|
||||
|
||||
app.use(`/uploads`, express.static(uploadDir))
|
||||
|
||||
return app
|
||||
export const config: MiddlewaresConfig = {
|
||||
routes: [
|
||||
{
|
||||
matcher: "/uploads",
|
||||
middlewares: [express.static(uploadDir)],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -8,20 +8,20 @@ In this document, you'll get an overview of Medusa's architecture to better unde
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
Medusa's core package `@medusajs/medusa` is a Node.js backend built on top of [Express](https://expressjs.com/). It combines all the [Commerce Modules](../../modules/overview.mdx) that Medusa provides. Commerce Modules are ecommerce features that can be used as building blocks in an ecommerce ecosystem. Product is an example of a Commerce Module.
|
||||
Medusa's core package `@medusajs/medusa` is a Node.js headless server. It combines all the [Commerce Modules](../../modules/overview.mdx) that Medusa provides. Commerce Modules are ecommerce features that can be used as building blocks in an ecommerce ecosystem. Product is an example of a Commerce Module.
|
||||
|
||||

|
||||

|
||||
|
||||
The backend connects to a database, such as [PostgreSQL](https://www.postgresql.org/), to store the ecommerce store’s data. The tables in that database are represented by [Entities](../entities/overview.mdx), built on top of [Typeorm](https://typeorm.io/). Entities can also be reflected in the database using [Migrations](../entities/migrations/overview.mdx).
|
||||
|
||||
The retrieval, manipulation, and other utility methods related to that entity are created inside a [Service](../services/overview.mdx). Services are TypeScript or JavaScript classes that, along with other resources, can be accessed throughout the Medusa backend through [dependency injection](./dependency-injection.md).
|
||||
|
||||
The backend does not have any tightly-coupled frontend. Instead, it exposes [Endpoints](../endpoints/overview.mdx) which are REST APIs that frontends such as an admin or a storefront can use to communicate with the backend. Endpoints are [Express routes](https://expressjs.com/en/guide/routing.html).
|
||||
The backend doesn't have any tightly-coupled frontend. Instead, it exposes [API Routes](../api-routes/overview.mdx) which are REST APIs that frontends such as an admin or a storefront can use to communicate with the backend.
|
||||
|
||||
Medusa also uses an [Events Architecture](../events/index.mdx) to trigger and handle events. Events are triggered when a specific action occurs, such as when an order is placed. To manage this events system, Medusa connects to a service that implements a pub/sub model, such as [Redis](https://redis.io/).
|
||||
|
||||
Events can be handled using [Subscribers](../events/subscribers.mdx). Subscribers are TypeScript or JavaScript classes that add their methods as handlers for specific events. These handler methods are only executed when an event is triggered.
|
||||
|
||||
You can create any of the resources in the backend’s architecture, such as entities, endpoints, services, and more, as part of your custom development without directly modifying the backend itself. The Medusa backend uses [loaders](../loaders/overview.mdx) to load the backend’s resources, as well as your custom resources and resources in [Plugins](../plugins/overview.mdx).
|
||||
You can create any of the resources in the backend’s architecture, such as entities, API Routes, services, and more, as part of your custom development without directly modifying the backend itself. The Medusa backend uses [loaders](../loaders/overview.mdx) to load the backend’s resources, as well as your custom resources and resources in [Plugins](../plugins/overview.mdx).
|
||||
|
||||
You can package your customizations into Plugins to reuse them in different Medusa backends or publish them for others to use. You can also install existing plugins into your Medusa backend.
|
||||
|
||||
@@ -16,7 +16,7 @@ Generally, all resources are registered in a container. Then, whenever a class d
|
||||
|
||||
### Medusa’s Dependency Container
|
||||
|
||||
Medusa uses a dependency container to register essential resources of the backend. You can then access these resources in classes and endpoints using the dependency container.
|
||||
Medusa uses a dependency container to register essential resources of the backend. You can then access these resources in classes and API Routes using the dependency container.
|
||||
|
||||
For example, if you create a custom service, you can access any other service registered in Medusa in your service’s constructor. That includes Medusa’s core services, services defined in plugins, or other services that you create on your backend.
|
||||
|
||||
@@ -28,7 +28,7 @@ To manage dependency injections, Medusa uses [Awilix](https://github.com/jeffijo
|
||||
|
||||
When you run the Medusa backend, a container of the type `MedusaContainer` is created. This type extends the [AwilixContainer](https://github.com/jeffijoe/awilix#the-awilixcontainer-object) object.
|
||||
|
||||
The backend then registers all important resources in the container, which makes them accessible in classes and endpoints.
|
||||
The backend then registers all important resources in the container, which makes them accessible in classes and API Routes.
|
||||
|
||||
---
|
||||
|
||||
@@ -695,11 +695,11 @@ Its camel-case name.
|
||||
|
||||
## Resolve Resources
|
||||
|
||||
This section covers how to resolve resources from the dependency container to use them in endpoints and classes in general.
|
||||
This section covers how to resolve resources from the dependency container to use them in API Routes and classes in general.
|
||||
|
||||
### In Endpoints
|
||||
### In API Routes
|
||||
|
||||
To resolve resources, such as services, in endpoints, use the `req.scope.resolve` method. The method receives the registration name of the resource as a parameter.
|
||||
To resolve resources, such as services, in API Routes, use the `MedusaRequest` object's `scope.resolve` method. The method receives the registration name of the resource as a parameter.
|
||||
|
||||
For example:
|
||||
|
||||
@@ -707,7 +707,7 @@ For example:
|
||||
const logger = req.scope.resolve("logger")
|
||||
```
|
||||
|
||||
Please note that in endpoints some resources, such as repositories, are not available. Refer to the [repositories](../entities/repositories.md) documentation to learn how you can load them.
|
||||
Please note that in API Routes some resources, such as repositories, aren't available. Refer to the [repositories](../entities/repositories.md#api-routes) documentation to learn how you can load them.
|
||||
|
||||
### In Classes
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ yarn test
|
||||
|
||||
### Run API Integration Tests
|
||||
|
||||
API integration tests are used to test out Medusa’s core endpoints.
|
||||
API integration tests are used to test out Medusa’s core API Routes.
|
||||
|
||||
To run the API integration tests, run the following command in the root directory of the repository:
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ In this document, you'll learn what an idempotency key is in Medusa.
|
||||
|
||||
## Overview
|
||||
|
||||
An Idempotency Key is a unique, randomly generated key associated with an operation, such as the cart completion process. The idempotency key can be passed in the header of a request to an endpoint. This allows you to safely retry requests without accidentally performing the same operation twice.
|
||||
An Idempotency Key is a unique, randomly generated key associated with an operation, such as the cart completion process. The idempotency key can be passed in the header of a request to an API Route. This allows you to safely retry requests without accidentally performing the same operation twice.
|
||||
|
||||
For example, if a connection error occurs while the customer is completing their cart and placing an order, you can retry from the last recovery point before the error occurred.
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ In this document, you'll learn how to use the `IdempotencyKeyService`.
|
||||
|
||||
## Overview
|
||||
|
||||
You can use the `IdempotencyKeyService` within your custom development to ensure that your custom endpoints and operations can be safely retried or continued if an error occurs. This guide is also useful if you're overriding an existing feature in Medusa that uses the `IdempotencyKeyService` and you want to maintain its usage, such as if you're overriding the cart completion strategy.
|
||||
You can use the `IdempotencyKeyService` within your custom development to ensure that your custom API Routes and operations can be safely retried or continued if an error occurs. This guide is also useful if you're overriding an existing feature in Medusa that uses the `IdempotencyKeyService` and you want to maintain its usage, such as if you're overriding the cart completion strategy.
|
||||
|
||||
The `IdempotencyKeyService` includes methods that can be used to create and update idempotency keys, among other functionalities.
|
||||
|
||||
@@ -17,18 +17,30 @@ The `IdempotencyKeyService` includes methods that can be used to create and upda
|
||||
|
||||
## Create Idempotency Key
|
||||
|
||||
You can create an idempotency key within an endpoint using the `create` method of the `IdempotencyKeyService`:
|
||||
You can create an idempotency key within an API Route using the `create` method of the `IdempotencyKeyService`:
|
||||
|
||||
```ts
|
||||
router.post("/custom-route", async (req, res) => {
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import { IdempotencyKeyService } from "@medusajs/medusa"
|
||||
|
||||
export const POST = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
// ...
|
||||
const idempotencyKeyService = req.scope.resolve<
|
||||
IdempotencyKeyService
|
||||
>("idempotencyKeyService")
|
||||
const idempotencyKey = await idempotencyKeyService.create({
|
||||
request_method: req.method,
|
||||
request_params: req.params,
|
||||
request_path: req.path,
|
||||
})
|
||||
// ...
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
The method requires as a parameter an object having the following properties:
|
||||
@@ -41,9 +53,23 @@ The method handles generating the idempotency key value and saving the idempoten
|
||||
|
||||
Alternatively, you can use the `initializeRequest` method that allows you to retrieve an idempotency key based on the value passed in the `Idempotency-Key` header of the request if it exists, or create a new key otherwise. For example:
|
||||
|
||||
```ts
|
||||
router.post("/custom-route", async (req, res) => {
|
||||
```ts title=src/api/store/custom/route.ts
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
import {
|
||||
IdempotencyKeyService,
|
||||
} from "@medusajs/medusa"
|
||||
|
||||
export const POST = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
// ...
|
||||
const idempotencyKeyService = req.scope.resolve<
|
||||
IdempotencyKeyService
|
||||
>("idempotencyKeyService")
|
||||
const headerKey = req.get("Idempotency-Key") || ""
|
||||
|
||||
const idempotencyKey = await idempotencyKeyService
|
||||
@@ -54,7 +80,7 @@ router.post("/custom-route", async (req, res) => {
|
||||
req.path
|
||||
)
|
||||
// ...
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
The method requires the following parameters:
|
||||
|
||||
@@ -200,12 +200,12 @@ The `to` and `data` properties are used in the `NotificationService` in Medusa
|
||||
|
||||
### resendNotification
|
||||
|
||||
Using the [Resend Notification endpoint](https://docs.medusajs.com/api/admin#notifications_postnotificationsnotificationresend), an admin user can resend a Notification to the customer. The [`NotificationService`](../../references/services/classes/NotificationService.md) in Medusa’s core then executes the `resendNotification` method in your Notification Provider.
|
||||
Using the [Resend Notification API Route](https://docs.medusajs.com/api/admin#notifications_postnotificationsnotificationresend), an admin user can resend a Notification to the customer. The [`NotificationService`](../../references/services/classes/NotificationService.md) in Medusa’s core then executes the `resendNotification` method in your Notification Provider.
|
||||
|
||||
This method receives three parameters:
|
||||
|
||||
1. `notification`: This is the original Notification record that was created after you sent the notification with `sendNotification`. You can get an overview of the entity and its attributes in the [architecture overview](./overview.mdx#notification-entity-overview), but most notably it includes the `to` and `data` attributes which are populated originally using the `to` and `data` properties of the object you return in `sendNotification`.
|
||||
2. `config`: In the Resend Notification endpoint you may specify an alternative receiver of the notification using the `to` request body parameter. For example, you may want to resend the order confirmation email to a different email. If that’s the case, you have access to it in the `config` parameter object. Otherwise, `config` will be an empty object.
|
||||
2. `config`: In the Resend Notification API Route you may specify an alternative receiver of the notification using the `to` request body parameter. For example, you may want to resend the order confirmation email to a different email. If that’s the case, you have access to it in the `config` parameter object. Otherwise, `config` will be an empty object.
|
||||
3. `attachmentGenerator`: If you’ve previously attached a generator to the Notification Service using the [`registerAttachmentGenerator`](../../references/services/classes/NotificationService.md#registerattachmentgenerator) method, you have access to it here. You can use the `attachmentGenerator` to generate on-demand invoices or other documents. The default value of this parameter is null.
|
||||
|
||||
Similarly to the `sendNotification` method, this method must return an object containing two properties:
|
||||
@@ -323,21 +323,21 @@ After placing an order, you can see in your console the message “Notification
|
||||
|
||||
## Test Resending Notifications with your Notification Provider
|
||||
|
||||
To test resending a notification, first, retrieve the ID of the notification you just sent using the [List Notifications admin endpoint](https://docs.medusajs.com/api/admin#notifications_getnotifications). You can pass as a body parameter the `to` or `event_name` parameters to filter out the notification you just sent.
|
||||
To test resending a notification, first, retrieve the ID of the notification you just sent using the [List Notifications API Route](https://docs.medusajs.com/api/admin#notifications_getnotifications). You can pass as a body parameter the `to` or `event_name` parameters to filter out the notification you just sent.
|
||||
|
||||
:::tip
|
||||
|
||||
You must be authenticated as an admin user before sending this request. You can use the [Authenticate a User](https://docs.medusajs.com/api/admin#auth_postauth) endpoint to get authenticated.
|
||||
You must be authenticated as an admin user before sending this request. You can use the [Authenticate a User API Route](https://docs.medusajs.com/api/admin#auth_postauth) to get authenticated.
|
||||
|
||||
:::
|
||||
|
||||

|
||||
|
||||
Then, send a request to the [Resend Notification](https://docs.medusajs.com/api/admin#notifications_postnotificationsnotificationresend) endpoint using the ID retrieved from the previous request. You can pass the `to` parameter in the body to change the receiver of the notification. You should see the message “Notification Resent” in your console and if you implemented your own logic for resending the notification it will be resent.
|
||||
Then, send a request to the [Resend Notification API Route](https://docs.medusajs.com/api/admin#notifications_postnotificationsnotificationresend) using the ID retrieved from the previous request. You can pass the `to` parameter in the body to change the receiver of the notification. You should see the message “Notification Resent” in your console and if you implemented your own logic for resending the notification it will be resent.
|
||||
|
||||

|
||||
|
||||
This request returns the same notification object as the List Notifications endpoint, but it now has a new object in the `resends` array. This is the resent notification. If you supplied a `to` parameter in the request body, you should see its value in the `to` property of the resent notification object.
|
||||
This request returns the same notification object as the List Notifications API Route, but it now has a new object in the `resends` array. This is the resent notification. If you supplied a `to` parameter in the request body, you should see its value in the `to` property of the resent notification object.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ With Medusa you can create notifications as a reaction to a wide spectrum of eve
|
||||
|
||||
An example of a flow that can be implemented using Medusa's Notification API is automated return flows:
|
||||
|
||||
- A customer requests a return by sending a `POST` request to the `/store/returns` endpoint.
|
||||
- A customer requests a return by sending a `POST` request to the `/store/returns` API Route.
|
||||
- The Notification Provider listens to the `order.return_requested` event and sends an email to the customer with a return invoice and return label generated by the Fulfillment Provider.
|
||||
- The customer returns the items triggering the `return.received` event.
|
||||
- The Notification Provider listens to the `return.received` event and sends an email to the customer with confirmation that their items have been received and that a refund has been issued.
|
||||
|
||||
@@ -36,7 +36,14 @@ When you build a commerce application with Medusa, you’ll typically interact w
|
||||
For example, imagine an Inventory module that contains lightweight logic to increment and decrement stock levels for a Stock-Keeping Unit (SKU). In a commerce application, you typically want to associate the stock levels with a specific product. Medusa offers both an Inventory module and a Product module, and the core package creates associations between these modules and executing the related business logic. So, the core package contains code similar to this:
|
||||
|
||||
```ts
|
||||
async function handler(req, res) {
|
||||
import type {
|
||||
MedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/medusa"
|
||||
export const POST = async (
|
||||
req: MedusaRequest,
|
||||
res: MedusaResponse
|
||||
) => {
|
||||
// ...
|
||||
|
||||
// associate a product with an inventory item
|
||||
@@ -57,7 +64,7 @@ async function handler(req, res) {
|
||||
|
||||
The goal of orchestrating the modules is to expose an API that client applications, like websites or apps, can consume. By default, Medusa’s core package exposes a REST API that offers commerce functionalities similar to what other platforms give you.
|
||||
|
||||
The core package also holds the logic that allows developers to extend and add custom endpoints, among other available customizations.
|
||||
The core package also holds the logic that allows developers to extend and add custom API Routes, among other available customizations.
|
||||
|
||||
---
|
||||
|
||||
@@ -111,8 +118,8 @@ These concepts will guide you through your development and building customizatio
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/endpoints/overview',
|
||||
label: 'Endpoints',
|
||||
href: '/development/api-routes/overview',
|
||||
label: 'API Routes',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'REST APIs that frontends consume to communicate with the backend.'
|
||||
@@ -194,9 +201,9 @@ By installing a Module in your project and expose its APIs based on the framewor
|
||||
|
||||
Developers can use Medusa’s toolkit to create their ecommerce system. With the use of the [create-medusa-app](../create-medusa-app.mdx) command, developers can set up a Medusa Backend, Medusa admin, and a storefront.
|
||||
|
||||

|
||||

|
||||
|
||||
Developers can still benefit from customization opportunities here that Medusa provides. This includes creating resources such as endpoints and services, creating plugins, integrating third-party services, create a custom storefront, and more.
|
||||
Developers can still benefit from customization opportunities here that Medusa provides. This includes creating resources such as API Routes and services, creating plugins, integrating third-party services, create a custom storefront, and more.
|
||||
|
||||
### Your Own Use Case
|
||||
|
||||
|
||||
@@ -196,17 +196,11 @@ Make sure to delete these files if you're not using them in your plugin.
|
||||
|
||||
### Plugin Structure
|
||||
|
||||
While developing your plugin, you can create your TypeScript or JavaScript files under the `src` directory. This includes creating services, endpoints, migrations, and other resources.
|
||||
While developing your plugin, you can create your TypeScript or JavaScript files under the `src` directory. This includes creating services, API Routes, migrations, and other resources.
|
||||
|
||||
However, before you test the changes on a Medusa backend or publish your plugin, you must transpile your files and move them either to a `dist` directory or to the root of the plugin's directory.
|
||||
|
||||
For example, if you have an endpoint in `src/api/index.js`, after running the `build` or `watch` commands [as defined earlier](#recommended-change-scripts), the file should be transpiled into `dist/api/index.js` in your plugin's root. You can alternative transpile them into the `api/index.js` in your plugin's root.
|
||||
|
||||
:::note
|
||||
|
||||
It was previously required to output your files into the root of the plugin's directory (for example, `api/index.js` instead of `dist/api/index.js`). As of v1.8, you can either have your files in the root of the directory or under the `dist` directory.
|
||||
|
||||
:::
|
||||
For example, if you have an API Route in `src/api/store/custom/route.ts`, after running the `build` or `watch` commands [as defined earlier](#recommended-change-scripts), the file should be transpiled into `dist/api/store/custom/route.ts` in your plugin's root. You can alternative transpile them into the `api/store/custom/route.ts` in your plugin's root.
|
||||
|
||||
### Development Resources
|
||||
|
||||
@@ -233,11 +227,11 @@ This guide doesn't cover how to create different files and components. If you’
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/endpoints/create',
|
||||
label: 'Create an Endpoint',
|
||||
href: '/development/api-routes/create',
|
||||
label: 'Create an API Route',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to create an endpoint.'
|
||||
description: 'Learn how to create an API Route.'
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -364,27 +358,6 @@ class MyService extends TransactionBaseService {
|
||||
}
|
||||
```
|
||||
|
||||
You can also access the options in your plugin's endpoints. The second parameter that the function declared in `src/api/index.ts` receives is an object including your plugin's configurations.
|
||||
|
||||
For example:
|
||||
|
||||
```js title=src/api/index.ts
|
||||
// in an endpoint in your plugin
|
||||
export default (rootDirectory, options) => {
|
||||
// options contain the plugin options
|
||||
const router = Router()
|
||||
|
||||
router.get("/hello-world", (req, res) => {
|
||||
res.json({
|
||||
message:
|
||||
`Welcome to ${options.name ? options.name : "Medusa"}!`,
|
||||
})
|
||||
})
|
||||
|
||||
return router
|
||||
}
|
||||
```
|
||||
|
||||
:::tip
|
||||
|
||||
Make sure to include in the README of your plugin the options that can be passed to a plugin.
|
||||
|
||||
+8
-8
@@ -61,7 +61,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## List Publishable API Keys
|
||||
|
||||
You can retrieve a list of publishable API keys by sending a request to the [List Publishable API Keys](https://docs.medusajs.com/api/admin#publishable-api-keys_getpublishableapikeys) endpoint:
|
||||
You can retrieve a list of publishable API keys by sending a request to the [List Publishable API Keys route](https://docs.medusajs.com/api/admin#publishable-api-keys_getpublishableapikeys):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -152,7 +152,7 @@ You can learn more about pagination in the [API reference](https://docs.medusajs
|
||||
|
||||
## Create a Publishable API Key
|
||||
|
||||
You can create a publishable API key by sending a request to the [Create Publishable API Key](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeys) endpoint:
|
||||
You can create a publishable API key by sending a request to the [Create Publishable API Key route](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeys):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -231,7 +231,7 @@ It returns the created publishable API key in the response.
|
||||
|
||||
## Update a Publishable API Key
|
||||
|
||||
You can update a publishable API key’s details by sending a request to the [Update Publishable API Key](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikyspublishableapikey) endpoint:
|
||||
You can update a publishable API key’s details by sending a request to the [Update Publishable API Key route](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikyspublishableapikey):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -316,7 +316,7 @@ This request returns the update publishable API key object in the response.
|
||||
|
||||
Revoking a publishable API key does not remove it, but does not allow using it in future requests.
|
||||
|
||||
You can revoke a publishable API key by sending a request to the [Revoke Publishable API Key](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeyspublishableapikeyrevoke) endpoint:
|
||||
You can revoke a publishable API key by sending a request to the [Revoke Publishable API Key route](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeyspublishableapikeyrevoke):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -386,7 +386,7 @@ This request requires the ID of the publishable API key as a path parameter. It
|
||||
|
||||
## Delete a Publishable API Key
|
||||
|
||||
You can delete a publishable API key by sending a request to the [Delete Publishable API Key](https://docs.medusajs.com/api/admin#publishable-api-keys_deletepublishableapikeyspublishableapikey) endpoint:
|
||||
You can delete a publishable API key by sending a request to the [Delete Publishable API Key route](https://docs.medusajs.com/api/admin#publishable-api-keys_deletepublishableapikeyspublishableapikey):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -463,7 +463,7 @@ This section covers how to manage sales channels in a publishable API key. This
|
||||
|
||||
### List Sales Channels of a Publishable API Key
|
||||
|
||||
You can retrieve the list of sales channels associated with a publishable API key by sending a request to the [List Sales Channels](https://docs.medusajs.com/api/admin#sales-channels_getsaleschannels) endpoint:
|
||||
You can retrieve the list of sales channels associated with a publishable API key by sending a request to the [List Sales Channels API Route](https://docs.medusajs.com/api/admin#sales-channels_getsaleschannels):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -546,7 +546,7 @@ It returns an array of sales channels associated with the publishable API key in
|
||||
|
||||
### Add Sales Channels to Publishable API Key
|
||||
|
||||
You can add a sales channel to a publishable API key by sending a request to the [Add Sales Channels](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeysaleschannelschannelsbatch) endpoint:
|
||||
You can add a sales channel to a publishable API key by sending a request to the [Add Sales Channels API Route](https://docs.medusajs.com/api/admin#publishable-api-keys_postpublishableapikeysaleschannelschannelsbatch):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -656,7 +656,7 @@ This request returns the updated publishable API key in the response.
|
||||
|
||||
### Delete Sales Channels from a Publishable API Key
|
||||
|
||||
You can delete a sales channel from a publishable API key by sending a request to the [Delete Sales Channels](https://docs.medusajs.com/api/admin#publishable-api-keys_deletepublishableapikeysaleschannelschannelsbatch) endpoint:
|
||||
You can delete a sales channel from a publishable API key by sending a request to the [Delete Sales Channels API Route](https://docs.medusajs.com/api/admin#publishable-api-keys_deletepublishableapikeysaleschannelschannelsbatch):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
|
||||
@@ -13,7 +13,7 @@ In this document, you’ll learn about Publishable API Keys and their architectu
|
||||
|
||||
While using Medusa’s APIs, you might have to pass some query parameters for certain resources with every or most requests.
|
||||
|
||||
Taking Sales Channels as an example, you have to pass the Sales Channel’s ID as a query parameter to all the necessary endpoints, such as the List Products endpoint.
|
||||
Taking Sales Channels as an example, you have to pass the Sales Channel’s ID as a query parameter to all the necessary API Routes, such as the List Products API Route.
|
||||
|
||||
This is a tedious and error-prone process. This is where Publishable API Keys are useful.
|
||||
|
||||
|
||||
+2
-2
@@ -12,9 +12,9 @@ In this document, you'll learn how to use Publishable API Keys in client request
|
||||
|
||||
:::
|
||||
|
||||
## Default Behaviour In Product Store Endpoints
|
||||
## Default Behaviour In Product Store API Routes
|
||||
|
||||
If you don't pass a publishable API Key for the store endpoints `/store/products` and `/store/products/{product_id}`, the default sales channel of the store is assigned to the request.
|
||||
If you don't pass a publishable API Key for the store API Routes `/store/products` and `/store/products/{product_id}`, the default sales channel of the store is assigned to the request.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -321,11 +321,11 @@ class MySearchService extends AbstractSearchService {
|
||||
|
||||
This method is used to search through an index by a query.
|
||||
|
||||
In the Medusa backend, this method is used within the [Search Products endpoint](https://docs.medusajs.com/api/store#products_postproductssearch) to retrieve the search results.
|
||||
In the Medusa backend, this method is used within the [Search Products API Route](https://docs.medusajs.com/api/store#products_postproductssearch) to retrieve the search results.
|
||||
|
||||
This method accepts the following parameters:
|
||||
|
||||
1. `indexName`: the first parameter is a string indicating the index to search through. When using the Search Products endpoint, the index is the default index defined in the `IndexName` static property of the `ProductService`, which is `products`.
|
||||
1. `indexName`: the first parameter is a string indicating the index to search through. When using the Search Products API Route, the index is the default index defined in the `IndexName` static property of the `ProductService`, which is `products`.
|
||||
2. `query`: the second parameter is a string indicating the query to use to search through the documents.
|
||||
3. `options`: the third parameter is typically an object that can be used to pass any necessary options to the search engine.
|
||||
|
||||
@@ -406,7 +406,7 @@ Run your backend to test it out:
|
||||
npx medusa develop
|
||||
```
|
||||
|
||||
You can then send a request to the [Search Products endpoint](https://docs.medusajs.com/api/store#products_postproductssearch) to see if your search service returns any results.
|
||||
You can then send a request to the [Search Products API Route](https://docs.medusajs.com/api/store#products_postproductssearch) to see if your search service returns any results.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -11,11 +11,11 @@ In this document, you’ll learn what a search service is and how it’s used in
|
||||
|
||||
## Overview
|
||||
|
||||
A search service is used to manage search indices of searchable items, such as products, and providing results for search operations. Although the Medusa core provides basic search functionalities through its endpoints, a search service allows you to integrate third-party services for an optimized search experience and rich search functionalities.
|
||||
A search service is used to manage search indices of searchable items, such as products, and providing results for search operations. Although the Medusa core provides basic search functionalities through its API Routes, a search service allows you to integrate third-party services for an optimized search experience and rich search functionalities.
|
||||
|
||||
A search service is a service class that is defined in a TypeScript or JavaScript file, which is created in the `src/services` directory of your Medusa backend codebase or plugin. The class must extend the `AbstractSearchService` class imported from the `@medusajs/utils` package.
|
||||
|
||||
Using the [dependency container and injection](../fundamentals/dependency-injection.md), the Medusa backend will then use and resolve the search service within the backend’s search operations, such as when the [Search Products](https://docs.medusajs.com/api/store#products_postproductssearch) endpoint is used. You can also [resolve the service](../services/create-service.mdx#use-a-service) within your resources to trigger the search where necessary.
|
||||
Using the [dependency container and injection](../fundamentals/dependency-injection.md), the Medusa backend will then use and resolve the search service within the backend’s search operations, such as when the [Search Products API Route](https://docs.medusajs.com/api/store#products_postproductssearch) is used. You can also [resolve the service](../services/create-service.mdx#use-a-service) within your resources to trigger the search where necessary.
|
||||
|
||||
Medusa provides official plugins that you can install and use in your Medusa backend. Check out available search plugins [here](../../plugins/search/index.mdx).
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
---
|
||||
description: 'Learn how to create a service in Medusa. This guide also includes how to use services in other services, subscribers, and endpoints.'
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
@@ -18,7 +17,7 @@ To create a service, create a TypeScript or JavaScript file in `src/services` to
|
||||
|
||||
For example, if you want to create a service `PostService`, eventually registered as `postService`, create the file `post.ts` in `src/services` with the following content:
|
||||
|
||||
```ts title=/src/services/post.ts
|
||||
```ts title=src/services/post.ts
|
||||
import { TransactionBaseService } from "@medusajs/medusa"
|
||||
|
||||
class PostService extends TransactionBaseService {
|
||||
@@ -54,7 +53,7 @@ As the service extends the `TransactionBaseService` class, all resources registe
|
||||
|
||||
So, if you want your service to use another service, add it as part of your constructor’s dependencies and set it to a field inside your service’s class:
|
||||
|
||||
```ts title=/src/services/post.ts
|
||||
```ts title=src/services/post.ts
|
||||
import { ProductService } from "@medusajs/medusa"
|
||||
import { PostRepository } from "../repositories/post"
|
||||
|
||||
@@ -71,7 +70,7 @@ class PostService extends TransactionBaseService {
|
||||
|
||||
Then, you can use that service anywhere in your custom service. For example:
|
||||
|
||||
```ts title=/src/services/post.ts
|
||||
```ts title=src/services/post.ts
|
||||
class PostService extends TransactionBaseService {
|
||||
// ...
|
||||
async getProductCount() {
|
||||
@@ -92,7 +91,7 @@ However, to actually get an instance of the repository within the service's meth
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=/src/services/post.ts
|
||||
```ts title=src/services/post.ts
|
||||
import { PostRepository } from "../repositories/post"
|
||||
|
||||
class PostService extends TransactionBaseService {
|
||||
@@ -132,7 +131,7 @@ The data returned by the function passed as a parameter to the `atomicPhase_` me
|
||||
|
||||
For example, the `PostService`'s `create` method with the `atomicPhase_` method:
|
||||
|
||||
```ts title=/src/services/post.ts
|
||||
```ts title=src/services/post.ts
|
||||
class PostService extends TransactionBaseService {
|
||||
protected postRepository_: typeof PostRepository
|
||||
// ...
|
||||
@@ -170,7 +169,7 @@ There are three lifetime types:
|
||||
|
||||
You can set the lifetime of your service by setting the `LIFE_TIME` static property:
|
||||
|
||||
```ts title=/src/services/post.ts
|
||||
```ts title=src/services/post.ts
|
||||
import { TransactionBaseService } from "@medusajs/medusa"
|
||||
import { Lifetime } from "awilix"
|
||||
|
||||
@@ -189,7 +188,7 @@ Within your service, you may need to access the Medusa configuration exported fr
|
||||
|
||||
For example:
|
||||
|
||||
```ts title=/src/services/post.ts
|
||||
```ts title=src/services/post.ts
|
||||
import {
|
||||
ConfigModule,
|
||||
TransactionBaseService,
|
||||
@@ -218,7 +217,7 @@ export default PostService
|
||||
|
||||
## Pagination, Filtering, and Relations
|
||||
|
||||
Often, your service will provide methods that retrieve a list of items, which can be used by endpoints. In these methods, it can be helpful to provide filtering and pagination utilities that can be used by endpoints or any other resources utilizing this service.
|
||||
Often, your service will provide methods that retrieve a list of items, which can be used by API Routes. In these methods, it can be helpful to provide filtering and pagination utilities that can be used by API Routes or any other resources utilizing this service.
|
||||
|
||||
The `@medusajs/medusa` package provides the following generic types that you can use to create the signature of your method that accepts filtering and pagination parameters:
|
||||
|
||||
@@ -298,7 +297,7 @@ class PostService extends TransactionBaseService {
|
||||
}
|
||||
```
|
||||
|
||||
Then, any other resources such as endpoints or services that use this method can pass what relations to expand in the next parameter:
|
||||
Then, any other resources such as API Route or services that use this method can pass what relations to expand in the next parameter:
|
||||
|
||||
```ts
|
||||
await postService.retrieve(id, {
|
||||
@@ -314,7 +313,7 @@ When you need to throw errors in your service methods, it's recommended to use `
|
||||
|
||||
:::note
|
||||
|
||||
This assumes you're handling errors in your custom endpoints as explained [here](../endpoints/create.mdx#handle-errors).
|
||||
This assumes you're handling errors in your custom API Route as explained [here](../api-routes/create.mdx#handle-errors).
|
||||
|
||||
:::
|
||||
|
||||
@@ -378,9 +377,9 @@ class MyService extends TransactionBaseService {
|
||||
}
|
||||
```
|
||||
|
||||
### In an Endpoint
|
||||
### In an API Route
|
||||
|
||||
To use your custom service in an endpoint, you can use `req.scope.resolve` passing it the service’s registration name:
|
||||
To use your custom service in an API Route, you can use `MedusaRequest` object's `scope.resolve` method passing it the service’s registration name:
|
||||
|
||||
```ts
|
||||
const postService = req.scope.resolve("postService")
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
---
|
||||
description: 'Learn how to create a service in Medusa. This guide also includes how to use services in other services, subscribers, and endpoints.'
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ For example, you can use Medusa’s `productService` to get the list of products
|
||||
|
||||
In the Medusa backend, custom services are TypeScript or JavaScript files located in the `src/services` directory. Each service should be a class that extends the `TransactionBaseService` class from the core Medusa package `@medusajs/medusa`. Each file you create in `src/services` should hold one service and export it.
|
||||
|
||||
The file name is important as it determines the name of the service when you need to use it elsewhere. The name of the service will be registered in the dependency container as the camel-case version of the file name with `Service` appended to the end of the name. Other resources, such as other services or endpoints, will use that name when resolving the service from the dependency container.
|
||||
The file name is important as it determines the name of the service when you need to use it elsewhere. The name of the service will be registered in the dependency container as the camel-case version of the file name with `Service` appended to the end of the name. Other resources, such as other services or API Routes, will use that name when resolving the service from the dependency container.
|
||||
|
||||
For example, if the file name is `hello.ts`, the service will be registered as `helloService` in the dependency container. If the file name is `hello-world.ts`, the service name will be registered as `helloWorldService`.
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ In this document, you’ll learn how to override a strategy in a Medusa backend
|
||||
|
||||
The Medusa core defines and uses strategies for certain functionalities, which allows developers to override these functionalities and implement them as fits for their use case.
|
||||
|
||||
For example, the cart completion process is implemented within a `CartCompletionStrategy` that is used inside the Complete Cart endpoint. If you need to change the cart completion process, you can override the `CartCompletionStrategy` and implement your own strategy. The Medusa backend will then use your strategy instead of the one defined in the core.
|
||||
For example, the cart completion process is implemented within a `CartCompletionStrategy` that is used inside the Complete Cart API Route. If you need to change the cart completion process, you can override the `CartCompletionStrategy` and implement your own strategy. The Medusa backend will then use your strategy instead of the one defined in the core.
|
||||
|
||||
### Hierarchy of Strategy Resolution
|
||||
|
||||
|
||||
@@ -15,9 +15,9 @@ A strategy is an isolated piece of business logic that can be overridden and cus
|
||||
|
||||
For example, in the core `@medusajs/medusa` package, strategies are used to implement functionalities like cart completion and product import.
|
||||
|
||||
These strategy classes are then resolved in endpoints, services, or wherever needed using dependency injection and used to perform their designated functionality.
|
||||
These strategy classes are then resolved in API Routes, services, or wherever needed using dependency injection and used to perform their designated functionality.
|
||||
|
||||
For example, the `CartCompletionStrategy` is resolved in the Complete Cart endpoint that is defined in the core `@medusajs/medusa` package. It’s then used to complete the cart and place the order:
|
||||
For example, the `CartCompletionStrategy` is resolved in the Complete Cart API Route that is defined in the core `@medusajs/medusa` package. It’s then used to complete the cart and place the order:
|
||||
|
||||
```ts
|
||||
export default async (req, res) => {
|
||||
|
||||
@@ -160,6 +160,15 @@ Medusa provides the essential building blocks that developers can put together t
|
||||
Learn about all the new features and enhancements in Medusa.
|
||||
|
||||
<DocCardList colSize={4} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/api-routes/create',
|
||||
label: 'API Routes',
|
||||
customProps: {
|
||||
icon: Icons['computer-desktop-solid'],
|
||||
description: 'Create API Routes and middlewares with an improved developer experience.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: 'https://docs.medusajs.com/ui',
|
||||
@@ -182,19 +191,6 @@ Learn about all the new features and enhancements in Medusa.
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/admin/routes',
|
||||
label: 'Admin UI Routes',
|
||||
customProps: {
|
||||
icon: Icons['computer-desktop-solid'],
|
||||
description: 'Learn how you can customize the admin dashboard with admin UI routes.',
|
||||
badge: {
|
||||
variant: 'orange',
|
||||
children: 'Beta'
|
||||
}
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
<!-- vale docs.HeadingPunctuation = NO -->
|
||||
|
||||
@@ -89,7 +89,7 @@ You can follow [this guide](https://docs.medusajs.com/api/admin#authentication)
|
||||
|
||||
### Using cookies
|
||||
|
||||
Authentication using cookies is done automatically by Axios, which is used within the Medusa JS Client, when authenticating using the [auth](/references/js-client/classes/AuthResource) endpoints. After authentication, all subsequent calls will be authenticated.
|
||||
Authentication using cookies is done automatically by Axios, which is used within the Medusa JS Client, when authenticating using the [auth](/references/js-client/classes/AuthResource) API Routes. After authentication, all subsequent calls will be authenticated.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@ export default Products
|
||||
|
||||
In the example above, you import the `useProducts` hook from `medusa-react`. This hook, and every other query hook exposed by `medusa-react`, returns everything that `useQuery` [returns in Tanstack Query](https://tanstack.com/query/v4/docs/react/reference/useQuery), except for the `data` field.
|
||||
|
||||
Instead of the `data` field, the response data is flattened and is part of the hooks’ returned fields. In the example above, the List Products endpoint returns a `products` array. So, `useProducts` returns a `products` array along with other fields returned by `useQuery`.
|
||||
Instead of the `data` field, the response data is flattened and is part of the hooks’ returned fields. In the example above, the List Products API Route returns a `products` array. So, `useProducts` returns a `products` array along with other fields returned by `useQuery`.
|
||||
|
||||
If the request accepts any parameters, they can be passed as parameters to the `mutate` request. For example:
|
||||
|
||||
@@ -213,11 +213,11 @@ Learn more about how you can use mutations in [Tanstack Query’s documentation]
|
||||
|
||||
### Custom Hooks
|
||||
|
||||
Medusa React provides three utility hooks that allows developers to consume their admin custom endpoints using the same Medusa React methods and conventions.
|
||||
Medusa React provides three utility hooks that allows developers to consume their admin custom API Routes using the same Medusa React methods and conventions.
|
||||
|
||||
#### useAdminCustomQuery
|
||||
|
||||
The `useAdminCustomQuery` utility hook can be used to send a `GET` request to a custom endpoint in your Medusa backend and retrieve data. It's a generic function, so you can pass a type for the request and the response if you're using TypeScript in your development. The first type parameter is the type of the request body, and the second type parameter is the type of the expected response body:
|
||||
The `useAdminCustomQuery` utility hook can be used to send a `GET` request to a custom API Route in your Medusa backend and retrieve data. It's a generic function, so you can pass a type for the request and the response if you're using TypeScript in your development. The first type parameter is the type of the request body, and the second type parameter is the type of the expected response body:
|
||||
|
||||
```ts
|
||||
useAdminCustomQuery<RequestType, ResponseType>
|
||||
@@ -225,9 +225,9 @@ useAdminCustomQuery<RequestType, ResponseType>
|
||||
|
||||
The hook accepts the following parameters:
|
||||
|
||||
1. `path`: (required) the first parameter is a string indicating the path of your endpoint. For example, if you have custom endpoints that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically.
|
||||
1. `path`: (required) the first parameter is a string indicating the path of your API Route. For example, if you have custom API Routes that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically.
|
||||
2. `queryKey`: (required) the second parameter is a string used to generate query keys, which are used by Tanstack Query for caching. When a mutation related to this same key succeeds, the key will be automatically invalidated.
|
||||
3. `query`: (optional) the third parameter is an object that can be used to pass query parameters to the endpoint. For example, if you want to pass an `expand` query parameter you can pass it within this object. Each query parameter's name is a key in the object. There are no limitations on what the type of the value can be, so you can pass an array or simply a string as a value.
|
||||
3. `query`: (optional) the third parameter is an object that can be used to pass query parameters to the API Route. For example, if you want to pass an `expand` query parameter you can pass it within this object. Each query parameter's name is a key in the object. There are no limitations on what the type of the value can be, so you can pass an array or simply a string as a value.
|
||||
4. `options`: (optional) the fourth parameter is an object of [TanStack Query options](https://tanstack.com/query/v4/docs/react/reference/useQuery).
|
||||
|
||||
The request returns an object containing keys like `data` which is an object that includes the data returned in the response, and `isLoading` which is a boolean value indicating whether the request is still in progress. You can learn more about the returned object's properties in [TanStack Query's documentation](https://tanstack.com/query/v4/docs/react/reference/useQuery).
|
||||
@@ -343,7 +343,7 @@ export default AuthorsBlogPosts
|
||||
|
||||
#### useAdminCustomPost
|
||||
|
||||
The `useAdminCustomPost` utility hook can be used to send a `POST` request to a custom endpoint in your Medusa backend. It's a generic function, so you can pass a type for the request and the response if you're using TypeScript in your development. The first type parameter is the type of the request body, and the second type parameter is the type of the expected response body:
|
||||
The `useAdminCustomPost` utility hook can be used to send a `POST` request to a custom API Route in your Medusa backend. It's a generic function, so you can pass a type for the request and the response if you're using TypeScript in your development. The first type parameter is the type of the request body, and the second type parameter is the type of the expected response body:
|
||||
|
||||
```ts
|
||||
useAdminCustomPost<RequestType, ResponseType>
|
||||
@@ -351,9 +351,9 @@ useAdminCustomPost<RequestType, ResponseType>
|
||||
|
||||
The hook accepts the following parameters:
|
||||
|
||||
1. `path`: (required) the first parameter is a string indicating the path of your endpoint. For example, if you have custom endpoints that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically.
|
||||
1. `path`: (required) the first parameter is a string indicating the path of your API Route. For example, if you have custom API Routes that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically.
|
||||
2. `queryKey`: (required) the second parameter is a string used to generate query keys, which are used by Tanstack Query for caching. When the mutation succeeds, the key will be automatically invalidated.
|
||||
3. `relatedDomains`: (optional) the third parameter is an object that can be used to specify domains related to this custom hook. This will ensure that Tanstack Query invalides the keys for those domains when your custom mutations succeed. For example, if your custom endpoint is related to products, you can pass `["products"]` as the value of this parameter. Then, when you use your custom mutation and it succeeds, the product's key `adminProductKeys.all` will be invalidated automatically, and all products will be re-fetched.
|
||||
3. `relatedDomains`: (optional) the third parameter is an object that can be used to specify domains related to this custom hook. This will ensure that Tanstack Query invalides the keys for those domains when your custom mutations succeed. For example, if your custom API Route is related to products, you can pass `["products"]` as the value of this parameter. Then, when you use your custom mutation and it succeeds, the product's key `adminProductKeys.all` will be invalidated automatically, and all products will be re-fetched.
|
||||
4. `options`: (optional) the fourth parameter is an object of [Mutation options](https://tanstack.com/query/v4/docs/react/reference/useMutation).
|
||||
|
||||
The request returns an object containing keys like `mutation` which is a function that can be used to send the `POST` request at a later point. You can learn more about the returned object's properties in [TanStack Query's documentation](https://tanstack.com/query/v4/docs/react/reference/useMutation).
|
||||
@@ -421,7 +421,7 @@ export default CreateBlogPost
|
||||
|
||||
#### useAdminCustomDelete
|
||||
|
||||
The `useAdminCustomDelete` utility hook can be used to send a `DELETE` request to a custom endpoint in your Medusa backend. It's a generic function, so you can pass a type for the expected response if you're using TypeScript in your development:
|
||||
The `useAdminCustomDelete` utility hook can be used to send a `DELETE` request to a custom API Route in your Medusa backend. It's a generic function, so you can pass a type for the expected response if you're using TypeScript in your development:
|
||||
|
||||
```ts
|
||||
useAdminCustomDelete<ResponseType>
|
||||
@@ -429,9 +429,9 @@ useAdminCustomDelete<ResponseType>
|
||||
|
||||
The hook accepts the following parameters:
|
||||
|
||||
1. `path`: (required) the first parameter is a string indicating the path of your endpoint. For example, if you have custom endpoints that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically.
|
||||
1. `path`: (required) the first parameter is a string indicating the path of your API Route. For example, if you have custom API Routes that begin with `/admin/vendors`, the value of this parameter would be `vendors`. The `/admin` prefix will be added automatically.
|
||||
2. `queryKey`: (required) the second parameter is a string used to generate query keys, which are used by Tanstack Query for caching. When the mutation succeeds, the key will be automatically invalidated.
|
||||
3. `relatedDomains`: (optional) the third parameter is an object that can be used to specify domains related to this custom hook. This will ensure that Tanstack Query invalides the keys for those domains when your custom mutations succeed. For example, if your custom endpoint is related to products, you can pass `["products"]` as the value of this parameter. Then, when you use your custom mutation and it succeeds, the product's key `adminProductKeys.all` will be invalidated automatically, and all products will be re-fetched.
|
||||
3. `relatedDomains`: (optional) the third parameter is an object that can be used to specify domains related to this custom hook. This will ensure that Tanstack Query invalides the keys for those domains when your custom mutations succeed. For example, if your custom API Route is related to products, you can pass `["products"]` as the value of this parameter. Then, when you use your custom mutation and it succeeds, the product's key `adminProductKeys.all` will be invalidated automatically, and all products will be re-fetched.
|
||||
4. `options`: (optional) the fourth parameter is an object of [Mutation options](https://tanstack.com/query/v4/docs/react/reference/useMutation).
|
||||
|
||||
The request returns an object containing keys like `mutation` which is a function that can be used to send the `DELETE` request at a later point. You can learn more about the returned object's properties in [TanStack Query's documentation](https://tanstack.com/query/v4/docs/react/reference/useMutation).
|
||||
|
||||
+4
-4
@@ -162,13 +162,13 @@ class MyFulfillmentService extends AbstractFulfillmentService {
|
||||
|
||||
### getFulfillmentOptions
|
||||
|
||||
This method is used when retrieving the list of fulfillment options available in a region, particularly by the [List Fulfillment Options endpoint](https://docs.medusajs.com/api/admin#regions_getregionsregionfulfillmentoptions).
|
||||
This method is used when retrieving the list of fulfillment options available in a region, particularly by the [List Fulfillment Options API Route](https://docs.medusajs.com/api/admin#regions_getregionsregionfulfillmentoptions).
|
||||
|
||||
For example, if you’re integrating UPS as a fulfillment provider, you might support two fulfillment options: UPS Express Shipping and UPS Access Point. Each of these options can have different data associated with them.
|
||||
|
||||
This method is expected to return an array of options. These options don't have any required format.
|
||||
|
||||
Later on, these options can be used when creating a shipping option, such as when using the [Create Shipping Option endpoint](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions). The chosen fulfillment option, which is one of the items in the array returned by this method, will be set in the `data` object of the shipping option.
|
||||
Later on, these options can be used when creating a shipping option, such as when using the [Create Shipping Option API Route](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions). The chosen fulfillment option, which is one of the items in the array returned by this method, will be set in the `data` object of the shipping option.
|
||||
|
||||
For example:
|
||||
|
||||
@@ -190,7 +190,7 @@ class MyFulfillmentService extends AbstractFulfillmentService {
|
||||
|
||||
### validateOption
|
||||
|
||||
Once the admin creates the shipping option, the data of the shipping option will be validated first using this method. This method is called when the [Create Shipping Option endpoint](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions) is used.
|
||||
Once the admin creates the shipping option, the data of the shipping option will be validated first using this method. This method is called when the [Create Shipping Option API Route](https://docs.medusajs.com/api/admin#shipping-options_postshippingoptions) is used.
|
||||
|
||||
This method accepts the `data` object that is sent in the body of the request, basically, the `data` object of the shipping option. You can use this data to validate the shipping option before it is saved.
|
||||
|
||||
@@ -223,7 +223,7 @@ This method accepts three parameters:
|
||||
|
||||
You can use these parameters to validate the chosen shipping option. For example, you can check if the `data` object passed as a second parameter includes all data needed to fulfill the shipment later on.
|
||||
|
||||
If any of the data is invalid, you can throw an error. This error will stop Medusa from creating a shipping method and the error message will be returned as a result to the endpoint.
|
||||
If any of the data is invalid, you can throw an error. This error will stop Medusa from creating a shipping method and the error message will be returned as a result of the API Route.
|
||||
|
||||
If everything is valid, this method must return an object that will be stored in the `data` property of the shipping method to be created. So, make sure the value you return contains everything you need to fulfill the shipment later on.
|
||||
|
||||
|
||||
@@ -510,7 +510,7 @@ class MyPaymentService extends AbstractPaymentProcessor {
|
||||
|
||||
This method is used to capture the payment amount of an order. This is typically triggered manually by the store operator from the admin.
|
||||
|
||||
This method is also used for capturing payments of a swap of an order, or when the [Capture Payment](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentcapture) endpoint is called.
|
||||
This method is also used for capturing payments of a swap of an order, or when a request is sent to the [Capture Payment API Route](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentcapture).
|
||||
|
||||
You can utilize this method to interact with the third-party provider and perform any actions necessary to capture the payment.
|
||||
|
||||
@@ -538,7 +538,7 @@ class MyPaymentService extends AbstractPaymentProcessor {
|
||||
|
||||
This method is used to refund an order’s payment. This is typically triggered manually by the store operator from the admin. The refund amount might be the total order amount or part of it.
|
||||
|
||||
This method is also used for refunding payments of a swap or a claim of an order, or when the [Refund Payment](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentrefunds) endpoint is called.
|
||||
This method is also used for refunding payments of a swap or a claim of an order, or when a request is sent to the [Refund Payment API Route](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentrefunds).
|
||||
|
||||
You can utilize this method to interact with the third-party provider and perform any actions necessary to refund the payment.
|
||||
|
||||
|
||||
+2
-2
@@ -85,7 +85,7 @@ In the above example, you inject the `IdempotencyKeyService` in the constructor.
|
||||
|
||||
## Step 2: Implement the complete Method
|
||||
|
||||
The cart completion strategy is required to implement a single method: the `complete` method. This method is used in the [Complete Cart endpoint](https://docs.medusajs.com/api/store#carts_postcartscartcomplete) to handle the logic of completing the cart.
|
||||
The cart completion strategy is required to implement a single method: the `complete` method. This method is used in the [Complete Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscartcomplete) to handle the logic of completing the cart.
|
||||
|
||||
The method accepts three parameters:
|
||||
|
||||
@@ -120,7 +120,7 @@ Run your backend to test it out:
|
||||
npx medusa develop
|
||||
```
|
||||
|
||||
Then, try out your strategy using the Complete Cart endpoint. You should see the logic you implemented used for completing the cart.
|
||||
Then, try out your strategy using the Complete Cart API Route. You should see the logic you implemented used for completing the cart.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ The cart’s totals are retrieved by default in all the [cart’s store APIs](ht
|
||||
|
||||
The cart completion functionality is implemented inside the strategy `cartCompletionStrategy`. This allows you to customize how the process is implemented in your store.
|
||||
|
||||
You can initiate the cart completion process by sending a request to the [Complete Cart endpoint](https://docs.medusajs.com/api/store#carts_postcartscartcomplete).
|
||||
You can initiate the cart completion process by sending a request to the [Complete Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscartcomplete).
|
||||
|
||||
### Idempotency Key
|
||||
|
||||
|
||||
+8
-8
@@ -60,7 +60,7 @@ In this step, the customer generally enters their shipping info, then chooses th
|
||||
|
||||
### Add Shipping Address
|
||||
|
||||
After the customer enters their shipping address information, you must send a `POST` request to the [Update a Cart](https://docs.medusajs.com/api/store#carts_postcartscart) API endpoint:
|
||||
After the customer enters their shipping address information, you must send a `POST` request to the [Update a Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscart):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -164,7 +164,7 @@ The request returns the updated cart, with the new shipping address available in
|
||||
|
||||
After updating the cart with the customer’s address, the list of available [shipping options](../shipping.md#shipping-option) for that cart might change. So, you should retrieve the updated list of options.
|
||||
|
||||
You can retrieve the list of shipping options by sending a `GET` request to the [Retrieve Shipping Options for Cart API](https://docs.medusajs.com/api/store#shipping-options_getshippingoptionscartid) endpoint:
|
||||
You can retrieve the list of shipping options by sending a `GET` request to the [Retrieve Shipping Options for Cart API Route](https://docs.medusajs.com/api/store#shipping-options_getshippingoptionscartid):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -234,7 +234,7 @@ The request accepts the ID of the cart as a path parameter. It returns the array
|
||||
|
||||
### Choose Shipping Option
|
||||
|
||||
Once the customer chooses one of the available shipping options, send a `POST` request to the [Add a Shipping Method](https://docs.medusajs.com/api/store#carts_postcartscartshippingmethod) API endpoint. This will create a [shipping method](../shipping.md#shipping-method) based on the shipping option chosen and will associate it with the customer’s cart:
|
||||
Once the customer chooses one of the available shipping options, send a `POST` request to the [Add a Shipping Method API Route](https://docs.medusajs.com/api/store#carts_postcartscartshippingmethod). This will create a [shipping method](../shipping.md#shipping-method) based on the shipping option chosen and will associate it with the customer’s cart:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -308,7 +308,7 @@ In this step, the customer generally chooses a payment method to complete their
|
||||
|
||||
When the page opens and before the payment providers are displayed to the customer to choose from, you must create the [payment sessions](../payment.md#payment-session) for the current cart. Each payment provider will have a payment session associated with it. These payment sessions will be used later when the customer chooses the payment provider they want to complete their purchase with.
|
||||
|
||||
To initialize the payment sessions, send a `POST` request to the [Initialize Payment Sessions](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsession) API endpoint:
|
||||
To initialize the payment sessions, send a `POST` request to the [Initialize Payment Sessions API Route](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsession):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -372,11 +372,11 @@ fetch(`<BACKEND_URL>/store/carts/${cartId}/payment-sessions`, {
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint accepts the ID of the cart as a path parameter. It returns the updated cart with the initialized payment sessions available on `cart.payment_sessions`.
|
||||
This API Route accepts the ID of the cart as a path parameter. It returns the updated cart with the initialized payment sessions available on `cart.payment_sessions`.
|
||||
|
||||
### Select Payment Session
|
||||
|
||||
When the customer chooses the payment processor they want to complete purchase with, you should select the payment session associated with that payment processor. To do that, send a `POST` request to the [Select a Payment Session](https://docs.medusajs.comapi/store#carts_postcartscartpaymentsession) API endpoint:
|
||||
When the customer chooses the payment processor they want to complete purchase with, you should select the payment session associated with that payment processor. To do that, send a `POST` request to the [Select a Payment Session API Route](https://docs.medusajs.comapi/store#carts_postcartscartpaymentsession):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -451,7 +451,7 @@ If you have one payment processor or if only one payment processor is available
|
||||
|
||||
This step is optional and is only necessary for some payment processors. As mentioned in the [Payment Architecture](../payment.md#overview) documentation, the `PaymentSession` model has a `data` attribute that holds any data required for the Payment Processor to perform payment operations such as capturing payment.
|
||||
|
||||
If you need to update that data at any point before the purchase is made, send a request to [Update a Payment Session](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsessionupdate) API endpoint:
|
||||
If you need to update that data at any point before the purchase is made, send a request to [Update a Payment Session API Route](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsessionupdate):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -537,7 +537,7 @@ It returns the updated cart. You can access the payment session's data on `cart.
|
||||
|
||||
The last step is to place the order by completing the cart. When you complete the cart, your Medusa backend will try to authorize the payment first, then place the order if the authorization is successful. So, you should perform any necessary action with your payment processor first to make sure the authorization is successful when you send the request to complete the cart.
|
||||
|
||||
To complete a cart, send a `POST` request to the [Complete a Cart](https://docs.medusajs.com/api/store#carts_postcartscartcomplete) API endpoint:
|
||||
To complete a cart, send a `POST` request to the [Complete a Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscartcomplete):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
|
||||
@@ -48,7 +48,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## Create Customer Groups
|
||||
|
||||
You can create a customer group by sending a request to the Create Customer Group endpoint:
|
||||
You can create a customer group by sending a request to the Create Customer Group API Route:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -131,7 +131,7 @@ This request requires the `name` parameter and optionally accepts the `metadata`
|
||||
|
||||
## List Customer Groups
|
||||
|
||||
You can get a list of all customer groups by sending a request to the List Customer Groups endpoint:
|
||||
You can get a list of all customer groups by sending a request to the List Customer Groups API Route:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -212,7 +212,7 @@ You can also pass filters and other selection query parameters to the request. C
|
||||
|
||||
## Retrieve a Customer Group
|
||||
|
||||
You can retrieve a single customer group by sending a request to the Get a Customer Group endpoint:
|
||||
You can retrieve a single customer group by sending a request to the Get a Customer Group API Route:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -279,7 +279,7 @@ This request accepts the ID of the customer group to retrieve as a path paramete
|
||||
|
||||
## Update a Customer Group
|
||||
|
||||
You can update a customer group’s data by sending a request to the Update Customer Group endpoint:
|
||||
You can update a customer group’s data by sending a request to the Update Customer Group API Route:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -373,7 +373,7 @@ This request accepts the ID of the customer group as a path parameter, and optio
|
||||
|
||||
## Delete Customer Group
|
||||
|
||||
You can delete a customer group by sending a request to the Delete a Customer Group endpoint:
|
||||
You can delete a customer group by sending a request to the Delete a Customer Group API Route:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -443,7 +443,7 @@ This request accepts the ID of the customer group to delete as a path parameter.
|
||||
|
||||
### Add Customer to Group
|
||||
|
||||
You can add a customer to a group by sending a request to the Customer Group’s Add Customer endpoint:
|
||||
You can add a customer to a group by sending a request to the Customer Group’s Add Customer API Route:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -543,7 +543,7 @@ This request accepts the ID of the customer group as a path parameter. In its bo
|
||||
|
||||
### List Customers
|
||||
|
||||
You can retrieve a list of all customers in a customer group using the List Customers endpoint:
|
||||
You can retrieve a list of all customers in a customer group using the List Customers API Route:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -626,7 +626,7 @@ Removing customers from a group does not remove them entirely. They’ll still b
|
||||
|
||||
:::
|
||||
|
||||
You can remove customers from a customer group by sending a request to the Remove Customers endpoint:
|
||||
You can remove customers from a customer group by sending a request to the Remove Customers API Route:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
|
||||
@@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## List Customers
|
||||
|
||||
You can show a list of customers by sending a request to the [List Customers](https://docs.medusajs.com/api/admin#customers_getcustomers) endpoint:
|
||||
You can show a list of customers by sending a request to the [List Customers API Route](https://docs.medusajs.com/api/admin#customers_getcustomers):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -139,7 +139,7 @@ You can learn more about pagination in the [API reference](https://docs.medusajs
|
||||
|
||||
Admins can create customer accounts. They have to supply the customer’s credentials and basic info.
|
||||
|
||||
You can create a customer account by sending a request to the [Create a Customer](https://docs.medusajs.com/api/admin#customers_postcustomers) endpoint:
|
||||
You can create a customer account by sending a request to the [Create a Customer API Route](https://docs.medusajs.com/api/admin#customers_postcustomers):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -246,7 +246,7 @@ The request returns the created customer object in the response.
|
||||
|
||||
An admin can edit a customer’s basic information and credentials.
|
||||
|
||||
You can edit a customer’s information by sending a request to the [Update a Customer](https://docs.medusajs.com/api/admin#customers_postcustomerscustomer) endpoint:
|
||||
You can edit a customer’s information by sending a request to the [Update a Customer API Route](https://docs.medusajs.com/api/admin#customers_postcustomerscustomer):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
|
||||
+12
-12
@@ -12,7 +12,7 @@ In this document, you’ll learn how to implement customer account functionaliti
|
||||
|
||||
## Overview
|
||||
|
||||
Medusa provides the necessary functionalities and endpoints to allow integrating essential customer features. Customers can create accounts to manage their information and keep track of their orders.
|
||||
Medusa provides the necessary functionalities and API Routes to allow integrating essential customer features. Customers can create accounts to manage their information and keep track of their orders.
|
||||
|
||||
### Scenario
|
||||
|
||||
@@ -58,7 +58,7 @@ If you follow the Medusa React code blocks, it's assumed you already have [Medus
|
||||
|
||||
A customer can register with an email and a password to store and manage their data.
|
||||
|
||||
You can register a new customer by sending a request to the [Create a Customer](https://docs.medusajs.com/api/store#customers_postcustomers) endpoint:
|
||||
You can register a new customer by sending a request to the [Create a Customer API Route](https://docs.medusajs.com/api/store#customers_postcustomers):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -135,7 +135,7 @@ fetch(`<BACKEND_URL>/store/customers`, {
|
||||
|
||||
This request requires the following body parameters:
|
||||
|
||||
- `email`: An email used to log in after registration. This email must be unique. You can check if an email is unique using the “[Check if email exists](https://docs.medusajs.com/api/store#auth_getauthemail)” endpoint.
|
||||
- `email`: An email used to log in after registration. This email must be unique. You can check if an email is unique using the “[Check if email exists](https://docs.medusajs.com/api/store#auth_getauthemail)” API Route.
|
||||
- `password`: A password used to log in after registration.
|
||||
- `first_name`: The customer’s first name.
|
||||
- `last_name`: The customer’s last name.
|
||||
@@ -150,7 +150,7 @@ It returns the created customer object in the response.
|
||||
|
||||
A customer can log in to your store to manage their data and make purchases using their account.
|
||||
|
||||
You can log in a customer into your store by sending a request to the [Customer Login](https://docs.medusajs.com/api/store#auth_postauth) endpoint:
|
||||
You can log in a customer into your store by sending a request to the [Customer Login API Route](https://docs.medusajs.com/api/store#auth_postauth):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -199,7 +199,7 @@ However, if you’re using the Fetch API, you must include the option `credentia
|
||||
|
||||
## Log out a Customer
|
||||
|
||||
You can log out a customer by sending a request to the [Customer Logout](https://docs.medusajs.com/api/store#auth_deleteauth) endpoint:
|
||||
You can log out a customer by sending a request to the [Customer Logout API Route](https://docs.medusajs.com/api/store#auth_deleteauth):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -239,7 +239,7 @@ Customers might need to reset their password in case they forget it. To reset a
|
||||
|
||||
The customer must first enter their account’s email. Then, if an account with that email address exists, an email will be sent to that email address with a link that points the customer to step 2.
|
||||
|
||||
You can request to reset a customer’s password by sending a request to the [Request Password Reset](https://docs.medusajs.com/api/store#customers_postcustomerscustomerpasswordtoken) endpoint:
|
||||
You can request to reset a customer’s password by sending a request to the [Request Password Reset API Route](https://docs.medusajs.com/api/store#customers_postcustomerscustomerpasswordtoken):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -295,7 +295,7 @@ If the customer doesn’t receive an email after this request, make sure that yo
|
||||
|
||||
After the first step, the customer should receive an email with a link to a page in the storefront. This page should accept a `token` query parameter. Then, the customer should be prompted to enter their email and password.
|
||||
|
||||
You can then reset the customer’s password to the new password they enter by sending a request to the [Reset Password](https://docs.medusajs.com/api/store#customers_postcustomersresetpassword) endpoint:
|
||||
You can then reset the customer’s password to the new password they enter by sending a request to the [Reset Password API Route](https://docs.medusajs.com/api/store#customers_postcustomersresetpassword):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -350,7 +350,7 @@ If successful, this request returns the customer object in the response.
|
||||
|
||||
A logged-in customer can edit their info, such as their first name or email address.
|
||||
|
||||
You can edit a customer’s info using the [Update Customer](https://docs.medusajs.com/api/store#customers_postcustomerscustomer) endpoint:
|
||||
You can edit a customer’s info using the [Update Customer API Route](https://docs.medusajs.com/api/store#customers_postcustomerscustomer):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -435,7 +435,7 @@ The customer object returned in the requests mentioned in this document include
|
||||
|
||||
### Add a Shipping Address
|
||||
|
||||
You can add a shipping address to a customer’s account by sending a request to the [Add a Shipping Address](https://docs.medusajs.com/api/store#customers_postcustomerscustomeraddresses) endpoint:
|
||||
You can add a shipping address to a customer’s account by sending a request to the [Add a Shipping Address API Route](https://docs.medusajs.com/api/store#customers_postcustomerscustomeraddresses):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -511,7 +511,7 @@ This request returns the updated customer object in the response.
|
||||
|
||||
### Edit a Shipping Address
|
||||
|
||||
You can edit a customer’s shipping address using the [Update a Shipping Address](https://docs.medusajs.com/api/store#customers_postcustomerscustomeraddressesaddress) endpoint:
|
||||
You can edit a customer’s shipping address using the [Update a Shipping Address API Route](https://docs.medusajs.com/api/store#customers_postcustomerscustomeraddressesaddress):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -556,7 +556,7 @@ This request returns the updated customer object in the response.
|
||||
|
||||
### Delete a Shipping Address
|
||||
|
||||
You can delete a shipping address by sending a request to the [Delete an Address](https://docs.medusajs.com/api/store#customers_deletecustomerscustomeraddressesaddress) endpoint:
|
||||
You can delete a shipping address by sending a request to the [Delete an Address API Route](https://docs.medusajs.com/api/store#customers_deletecustomerscustomeraddressesaddress):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -595,7 +595,7 @@ This request requires the address’s ID as a path parameter. It returns in the
|
||||
|
||||
Logged-in customers can see their orders along with the orders’ details.
|
||||
|
||||
You can retrieve a customer’s orders by sending a request to the [List Orders](https://docs.medusajs.com/api/store#customers_getcustomerscustomerorders) endpoint:
|
||||
You can retrieve a customer’s orders by sending a request to the [List Orders API Route](https://docs.medusajs.com/api/store#customers_getcustomerscustomerorders):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
|
||||
@@ -64,7 +64,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## Create a Discount
|
||||
|
||||
You can create a discount by sending a request to the [Create Discount](https://docs.medusajs.com/api/admin#discounts_postdiscounts) endpoint:
|
||||
You can create a discount by sending a request to the [Create Discount API Route](https://docs.medusajs.com/api/admin#discounts_postdiscounts):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -202,7 +202,7 @@ This request returns the full `discount` object.
|
||||
|
||||
## Update Discount
|
||||
|
||||
You can update any of the discount’s information, configurations, and conditions by sending a request to the [Update Discount](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscount) endpoint.
|
||||
You can update any of the discount’s information, configurations, and conditions by sending a request to the [Update Discount API Route](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscount).
|
||||
|
||||
For example, you can update the discount’s description and status by sending the following request:
|
||||
|
||||
@@ -294,7 +294,7 @@ You can learn more about conditions and conditions types in the [Discount Archit
|
||||
|
||||
:::
|
||||
|
||||
You can send a request to the [Create Condition](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscountconditions) endpoint to create a condition in a discount:
|
||||
You can send a request to the [Create Condition API Route](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscountconditions) to create a condition in a discount:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -407,7 +407,7 @@ This request returns the full `discount` object in the response which includes a
|
||||
|
||||
### Retrieve Condition
|
||||
|
||||
You can retrieve a condition and its resources by sending a request to the [Get Condition](https://docs.medusajs.com/api/admin#discounts_getdiscountsdiscountconditionscondition) endpoint:
|
||||
You can retrieve a condition and its resources by sending a request to the [Get Condition API Route](https://docs.medusajs.com/api/admin#discounts_getdiscountsdiscountconditionscondition):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -506,7 +506,7 @@ In the previous example, you pass `expand=products` as a query parameter, which
|
||||
|
||||
### Update Condition
|
||||
|
||||
You can update a condition’s resources using the [Update Condition](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscountconditionscondition) endpoint. You can’t update a condition’s operator.
|
||||
You can update a condition’s resources using the [Update Condition API Route](https://docs.medusajs.com/api/admin#discounts_postdiscountsdiscountconditionscondition). You can’t update a condition’s operator.
|
||||
|
||||
For example, to update the products in a condition:
|
||||
|
||||
@@ -608,7 +608,7 @@ This request returns the full `discount` object with the updated condition in th
|
||||
|
||||
### Delete Condition
|
||||
|
||||
You can delete a condition by sending a request to the [Delete Condition](https://docs.medusajs.com/api/admin#discounts_deletediscountsdiscountconditionscondition) endpoint:
|
||||
You can delete a condition by sending a request to the [Delete Condition API Route](https://docs.medusajs.com/api/admin#discounts_deletediscountsdiscountconditionscondition):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -683,7 +683,7 @@ It returns the `discount` object in the response.
|
||||
|
||||
## Delete Discount
|
||||
|
||||
You can delete a discount by sending a request to the [Delete Discount](https://docs.medusajs.com/api/admin#discounts_deletediscountsdiscount) endpoint:
|
||||
You can delete a discount by sending a request to the [Delete Discount API Route](https://docs.medusajs.com/api/admin#discounts_deletediscountsdiscount):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
|
||||
@@ -59,11 +59,11 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
This section covers managing the gift card products. Each gift card can have unlimited denominations.
|
||||
|
||||
As gift cards are, before purchase, essentially products, you’ll be using product endpoints to manage them.
|
||||
As gift cards are, before purchase, essentially products, you’ll be using product API Routes to manage them.
|
||||
|
||||
### Retrieve Gift Card Product
|
||||
|
||||
You can retrieve the gift card products by sending a request to the [List Products](https://docs.medusajs.com/api/admin#products_getproducts) endpoint, but filtering the products with the `is_giftcard` flag:
|
||||
You can retrieve the gift card products by sending a request to the [List Products API Route](https://docs.medusajs.com/api/admin#products_getproducts), but filtering the products with the `is_giftcard` flag:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -146,13 +146,13 @@ curl -L -X GET '<BACKEND_URL>/admin/products?is_giftcard=true' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
The List Products endpoint accepts a variety of query parameters that can be used to filter the products. One of them is `is_giftcard`. When set to `true`, it will only retrieve the gift card products.
|
||||
The List Products API Route accepts a variety of query parameters that can be used to filter the products. One of them is `is_giftcard`. When set to `true`, it will only retrieve the gift card products.
|
||||
|
||||
The request returns the `products` array in the response which holds the gift card in it, if it’s available. It also returns [pagination fields](https://docs.medusajs.com/api/admin#pagination).
|
||||
|
||||
### Create Gift Card Product
|
||||
|
||||
You can create a gift card product by sending a request to the [Create a Product](https://docs.medusajs.com/api/admin#products_postproducts) endpoint:
|
||||
You can create a gift card product by sending a request to the [Create a Product API Route](https://docs.medusajs.com/api/admin#products_postproducts):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -353,7 +353,7 @@ Although you can create an unlimited number of gift cards, the admin dashboard's
|
||||
|
||||
After creating a gift card, merchants can update it or its denomination.
|
||||
|
||||
You can update a gift card product’s details by sending a request to the [Update a Product](https://docs.medusajs.com/api/admin#products_postproductsproduct) endpoint:
|
||||
You can update a gift card product’s details by sending a request to the [Update a Product API Route](https://docs.medusajs.com/api/admin#products_postproductsproduct):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -432,7 +432,7 @@ This request returns the updated gift card product in the response.
|
||||
|
||||
### Delete Gift Card Product
|
||||
|
||||
You can delete a gift card product by sending a request to the [Delete a Product](https://docs.medusajs.com/api/admin#products_deleteproductsproduct) endpoint:
|
||||
You can delete a gift card product by sending a request to the [Delete a Product API Route](https://docs.medusajs.com/api/admin#products_deleteproductsproduct):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -505,7 +505,7 @@ This section covers how to manage custom gift cards. You can create an unlimited
|
||||
|
||||
### List Custom Gift Cards
|
||||
|
||||
You can retrieve all custom gift cards by sending a request to the [List Gift Cards](https://docs.medusajs.com/api/admin#gift-cards_getgiftcards) endpoint:
|
||||
You can retrieve all custom gift cards by sending a request to the [List Gift Cards API Route](https://docs.medusajs.com/api/admin#gift-cards_getgiftcards):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -579,7 +579,7 @@ This request returns an array of `gift_cards` and [pagination fields](https://do
|
||||
|
||||
Merchants can create custom gift cards to send a reward or gift to the customer.
|
||||
|
||||
You can create a custom gift card by sending a request to the [Create a Gift Card](https://docs.medusajs.com/api/admin#gift-cards_postgiftcards) endpoint:
|
||||
You can create a custom gift card by sending a request to the [Create a Gift Card API Route](https://docs.medusajs.com/api/admin#gift-cards_postgiftcards):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -664,7 +664,7 @@ This request returns the created gift card object in the response.
|
||||
|
||||
Merchants can update any of the gift card’s properties, except for the value of the gift card.
|
||||
|
||||
You can update a gift card by sending a request to the [Update a Gift Card](https://docs.medusajs.com/api/admin#gift-cards_postgiftcardsgiftcard) endpoint:
|
||||
You can update a gift card by sending a request to the [Update a Gift Card API Route](https://docs.medusajs.com/api/admin#gift-cards_postgiftcardsgiftcard):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -745,7 +745,7 @@ This request returns the updated gift card object in the response.
|
||||
|
||||
### Delete Custom Gift Card
|
||||
|
||||
You can delete a custom gift card by sending a request to the [Delete a Gift Card](https://docs.medusajs.com/api/admin#gift-cards_deletegiftcardsgiftcard) endpoint:
|
||||
You can delete a custom gift card by sending a request to the [Delete a Gift Card API Route](https://docs.medusajs.com/api/admin#gift-cards_deletegiftcardsgiftcard):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
|
||||
@@ -58,7 +58,7 @@ In addition, this document doesn't cover how to implement checkout functionality
|
||||
|
||||
Customers should be able to view gift cards before they make the purchase. Gift cards are essentially products like any other.
|
||||
|
||||
You can retrieve the gift card product using the [List Products](https://docs.medusajs.com/api/store#products_getproducts) endpoint, but passing it the `is_giftcard` query parameter:
|
||||
You can retrieve the gift card product using the [List Products API Route](https://docs.medusajs.com/api/store#products_getproducts), but passing it the `is_giftcard` query parameter:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -147,7 +147,7 @@ The value of each denomination (or variant) is under the `prices` array. If you
|
||||
|
||||
After the customer purchases the gift card, they’ll receive a code to redeem that gift card. Using that code, the customer can also view the details of that gift card.
|
||||
|
||||
You can retrieve the details of a gift card by sending a request to the [Get Gift Card by Code](https://docs.medusajs.com/api/store#gift-cards_getgiftcardscode) endpoint:
|
||||
You can retrieve the details of a gift card by sending a request to the [Get Gift Card by Code API Route](https://docs.medusajs.com/api/store#gift-cards_getgiftcardscode):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -222,7 +222,7 @@ You can learn what other properties are available in the returned gift card obje
|
||||
|
||||
A customer can redeem more than one gift card during checkout. The cart’s totals will then be adjusted based on the applied gift card. The gift card’s amount isn’t actually used until the order is placed.
|
||||
|
||||
You can redeem a gift card during checkout by sending a request to the [Update Cart](https://docs.medusajs.com/api/store#carts_postcartscart) endpoint:
|
||||
You can redeem a gift card during checkout by sending a request to the [Update Cart API Route](https://docs.medusajs.com/api/store#carts_postcartscart):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -306,7 +306,7 @@ To add gift cards, you must pass the array `gift_cards`. Each item in the array
|
||||
|
||||
:::tip
|
||||
|
||||
The parameters passed in the update endpoint replace existing values. So, if you previously added a gift card, then tried adding another, you must include both in the `gift_cards` array.
|
||||
The parameters passed to the update API Route replace existing values. So, if you previously added a gift card, then tried adding another, you must include both in the `gift_cards` array.
|
||||
|
||||
:::
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## List Inventory Items
|
||||
|
||||
You can list inventory items by sending a request to the [List Inventory Items endpoint](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitems):
|
||||
You can list inventory items by sending a request to the [List Inventory Items API Route](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitems):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -126,7 +126,7 @@ curl -L -X GET '<BACKEND_URL>/admin/inventory-items' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint does not require any path or query parameters. You can, however, pass path parameters to search or filter inventory items. For example, you can get inventory items in a specific location by passing the `location_id` query parameter. You can learn more about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitems).
|
||||
This API Route doesn't require any path or query parameters. You can, however, pass path parameters to search or filter inventory items. For example, you can get inventory items in a specific location by passing the `location_id` query parameter. You can learn more about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitems).
|
||||
|
||||
This request returns an array of inventory item objects.
|
||||
|
||||
@@ -140,7 +140,7 @@ Inventory items are automatically created when a variant is created with `manage
|
||||
|
||||
:::
|
||||
|
||||
You can create an inventory item by sending a request to the [Create Inventory Item endpoint](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitems):
|
||||
You can create an inventory item by sending a request to the [Create Inventory Item API Route](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitems):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -211,7 +211,7 @@ curl -L -X POST '<BACKEND_URL>/admin/inventory-items' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires in the body parameter the `variant_id` parameter, which is the ID of the variant to create this inventory item for. You can also pass other inventory-related parameters, such as `sku`. You can learn more about other available parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitems).
|
||||
This API Route requires in the body parameter the `variant_id` parameter, which is the ID of the variant to create this inventory item for. You can also pass other inventory-related parameters, such as `sku`. You can learn more about other available parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitems).
|
||||
|
||||
This request returns the created inventory item as an object.
|
||||
|
||||
@@ -219,7 +219,7 @@ This request returns the created inventory item as an object.
|
||||
|
||||
## Retrieve Inventory Item
|
||||
|
||||
You can retrieve an inventory item by sending a request to the [Get Inventory Item endpoint](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitemsinventoryitem):
|
||||
You can retrieve an inventory item by sending a request to the [Get Inventory Item API Route](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitemsinventoryitem):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -281,7 +281,7 @@ curl -L -X GET '<BACKEND_URL>/admin/inventory-items/<ITEM_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint accepts the ID of the inventory item as a path parameter. You can also path query parameters such as [expand](https://docs.medusajs.com/api/admin#expanding-fields) and [fields](https://docs.medusajs.com/api/admin#selecting-fields).
|
||||
This API Route accepts the ID of the inventory item as a path parameter. You can also path query parameters such as [expand](https://docs.medusajs.com/api/admin#expanding-fields) and [fields](https://docs.medusajs.com/api/admin#selecting-fields).
|
||||
|
||||
The request returns the inventory item as an object.
|
||||
|
||||
@@ -289,7 +289,7 @@ The request returns the inventory item as an object.
|
||||
|
||||
## Update Inventory Item
|
||||
|
||||
You can update an inventory item by sending a request to the [Update Inventory Item endpoint](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitem):
|
||||
You can update an inventory item by sending a request to the [Update Inventory Item API Route](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitem):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -364,7 +364,7 @@ curl -L -X POST '<BACKEND_URL>/admin/inventory-items/<ITEM_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the inventory item’s ID as a path parameter. You can pass any of the inventory item’s attributes that you want to update in its body parameter. The example above updates the value of the `origin_country` attribute. You can learn more about available body parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitem).
|
||||
This API Route requires the inventory item’s ID as a path parameter. You can pass any of the inventory item’s attributes that you want to update in its body parameter. The example above updates the value of the `origin_country` attribute. You can learn more about available body parameters in the [API reference](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitem).
|
||||
|
||||
The request returns the updated inventory item as an object.
|
||||
|
||||
@@ -376,7 +376,7 @@ This section shows you the different ways you can manage inventory levels. Each
|
||||
|
||||
### List inventory levels
|
||||
|
||||
You can list inventory levels of an inventory item by sending a request to the [List inventory levels endpoint](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitemsinventoryitemlocationlevels):
|
||||
You can list inventory levels of an inventory item by sending a request to the [List inventory levels API Route](https://docs.medusajs.com/api/admin#inventory-items_getinventoryitemsinventoryitemlocationlevels):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -445,13 +445,13 @@ curl -L -X GET '<BACKEND_URL>/admin/inventory-items/<ITEM_ID>/location-levels' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of the inventory item as a path parameter. You can also pass [expand](https://docs.medusajs.com/api/admin#expanding-fields) and [fields](https://docs.medusajs.com/api/admin#selecting-fields) query parameters.
|
||||
This API Route requires the ID of the inventory item as a path parameter. You can also pass [expand](https://docs.medusajs.com/api/admin#expanding-fields) and [fields](https://docs.medusajs.com/api/admin#selecting-fields) query parameters.
|
||||
|
||||
The request returns the inventory item as an object. In that object, the list of inventory levels are available under the property `location_levels`.
|
||||
|
||||
### Create Inventory Level
|
||||
|
||||
You can create a location level by sending a request to the [Create Inventory Level endpoint](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitemlocationlevels):
|
||||
You can create a location level by sending a request to the [Create Inventory Level API Route](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitemlocationlevels):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -533,7 +533,7 @@ curl -L -X POST '<BACKEND_URL>/admin/inventory-items/<ITEM_ID>/location-levels'
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the inventory item ID as a path parameter. In the request body, it requires the following parameters:
|
||||
This API Route requires the inventory item ID as a path parameter. In the request body, it requires the following parameters:
|
||||
|
||||
- `location_id`: The ID of the location associated with this location level. This ID is typically available through using the stock location module.
|
||||
- `stocked_quantity`: A number indicating the item’s quantity in stock.
|
||||
@@ -544,7 +544,7 @@ This request returns the inventory item associated with the created location lev
|
||||
|
||||
### Update Location Level
|
||||
|
||||
You can update a location level by sending a request to the [Update Location Level endpoint](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitemlocationlevelslocationlevel):
|
||||
You can update a location level by sending a request to the [Update Location Level API Route](https://docs.medusajs.com/api/admin#inventory-items_postinventoryitemsinventoryitemlocationlevelslocationlevel):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -624,7 +624,7 @@ curl -L -X POST '<BACKEND_URL>/admin/inventory-items/<ITEM_ID>/location-levels/<
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires two path parameters: the first one being the ID of the inventory item, and the second one being the ID of the location.
|
||||
This API Route requires two path parameters: the first one being the ID of the inventory item, and the second one being the ID of the location.
|
||||
|
||||
In the body, you can optionally pass any of the location level’s attributes to update. In the example above, you update the `stocked_quantity` attribute of the location level.
|
||||
|
||||
@@ -632,7 +632,7 @@ The request returns the inventory item associated with the location level as an
|
||||
|
||||
### Delete Location Level
|
||||
|
||||
You can delete a location level of an inventory item by sending a request to the [Delete Location Level endpoint](https://docs.medusajs.com/api/admin#inventory-items_deleteinventoryitemsinventoryitelocationlevelslocation):
|
||||
You can delete a location level of an inventory item by sending a request to the [Delete Location Level API Route](https://docs.medusajs.com/api/admin#inventory-items_deleteinventoryitemsinventoryitelocationlevelslocation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -696,7 +696,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/inventory-items/<ITEM_ID>/location-levels
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires two path parameters: the first one being the inventory item’s ID and the second one being the location level’s ID.
|
||||
This API Route requires two path parameters: the first one being the inventory item’s ID and the second one being the location level’s ID.
|
||||
|
||||
The request returns the inventory item as an object.
|
||||
|
||||
@@ -704,7 +704,7 @@ The request returns the inventory item as an object.
|
||||
|
||||
## Delete Inventory Item
|
||||
|
||||
You can delete an inventory item by sending a request to the [Delete Inventory Item endpoint](https://docs.medusajs.com/api/admin#inventory-items_deleteinventoryitemsinventoryitem):
|
||||
You can delete an inventory item by sending a request to the [Delete Inventory Item API Route](https://docs.medusajs.com/api/admin#inventory-items_deleteinventoryitemsinventoryitem):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -765,7 +765,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/inventory-items/<ITEM_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the inventory item’s ID be passed as a path parameter.
|
||||
This API Route requires the inventory item’s ID be passed as a path parameter.
|
||||
|
||||
It returns the following fields in the response:
|
||||
|
||||
|
||||
+14
-14
@@ -70,13 +70,13 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
Using the reservations admin REST APIs, you can create an item allocation or reservation for any resource, and not just items in an order. This gives you more options in how you handle item allocations.
|
||||
|
||||
In this guide, however, the focus will be on how to use these endpoints for order-related functionalities.
|
||||
In this guide, however, the focus will be on how to use these API Routes for order-related functionalities.
|
||||
|
||||
### Create Item Allocation
|
||||
|
||||
Item allocations are created automatically for items that are associated with product variants having the `manage_inventory` attribute enabled. You typically don’t need to create an item allocation, unless you delete the previous item allocation.
|
||||
|
||||
You can create an item allocation by sending a request to the [Create a Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_postreservations):
|
||||
You can create an item allocation by sending a request to the [Create a Reservation API Route](https://docs.medusajs.com/api/admin#reservations_postreservations):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -159,7 +159,7 @@ curl -L -X POST '<BACKEND_URL>/admin/reservations' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the following body parameters:
|
||||
This API Route requires the following body parameters:
|
||||
|
||||
- `line_item_id`: The ID of the order’s line item the allocation is being created for.
|
||||
- `location_id`: The ID of the location the item is being allocated from.
|
||||
@@ -172,7 +172,7 @@ The request returns the created reservation as an object.
|
||||
|
||||
When listing item allocations, by default, you’ll be retrieving all item allocations in your commerce system. You can, however, provide optional fields to filter the item allocations retrieved.
|
||||
|
||||
You can retrieve the item allocations of a line item in an order using the [List Reservations endpoint](https://docs.medusajs.com/api/admin#reservations_getreservations):
|
||||
You can retrieve the item allocations of a line item in an order using the [List Reservations API Route](https://docs.medusajs.com/api/admin#reservations_getreservations):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -243,13 +243,13 @@ curl -L -X GET '<BACKEND_URL>/admin/reservations?line_item_id=<LINE_ITEM_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint does not require any path or query parameters. As mentioned earlier, you can pass query parameters to filter the reservations. In the code snippets above, you filter the reservations by a line item ID. You can, however, filter by other attributes, such as the ID of the location. You can refer to the [API reference](https://docs.medusajs.com/api/admin#reservations_getreservations) for a full list of query parameters.
|
||||
This API Route doesn't require any path or query parameters. As mentioned earlier, you can pass query parameters to filter the reservations. In the code snippets above, you filter the reservations by a line item ID. You can, however, filter by other attributes, such as the ID of the location. You can refer to the [API reference](https://docs.medusajs.com/api/admin#reservations_getreservations) for a full list of query parameters.
|
||||
|
||||
The request returns the reservations along with [pagination fields](https://docs.medusajs.com/api/admin#pagination).
|
||||
|
||||
### Retrieve Item Allocation
|
||||
|
||||
You can retrieve a single item allocation by its ID using the [Get a Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_getreservationsreservation):
|
||||
You can retrieve a single item allocation by its ID using the [Get a Reservation API Route](https://docs.medusajs.com/api/admin#reservations_getreservationsreservation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -309,13 +309,13 @@ curl -L -X GET '<BACKEND_URL>/admin/reservations/<RESERVATION_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the reservation’s ID as a path parameter.
|
||||
This API Route requires the reservation’s ID as a path parameter.
|
||||
|
||||
The request returns the reservation as an object.
|
||||
|
||||
### Update Item Allocation
|
||||
|
||||
You can update an item allocation to change the location to allocate from or the quantity to allocate by sending a request to the [Update Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_postreservationsreservation):
|
||||
You can update an item allocation to change the location to allocate from or the quantity to allocate by sending a request to the [Update Reservation API Route](https://docs.medusajs.com/api/admin#reservations_postreservationsreservation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -388,7 +388,7 @@ curl -L -X POST '<BACKEND_URL>/admin/reservations/<RESERVATION_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of the reservation as a path parameter.
|
||||
This API Route requires the ID of the reservation as a path parameter.
|
||||
|
||||
In the request body parameters, you can optionally pass any of the following parameters to make updates to the reservation:
|
||||
|
||||
@@ -402,7 +402,7 @@ The request returns the updated reservation as an object.
|
||||
|
||||
Deleting an item allocation means that the quantity that was previously reserved is no longer reserved.
|
||||
|
||||
You can delete an item allocation by sending a request to the [Delete Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_deletereservationsreservation):
|
||||
You can delete an item allocation by sending a request to the [Delete Reservation API Route](https://docs.medusajs.com/api/admin#reservations_deletereservationsreservation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -461,12 +461,12 @@ curl -L -X DELETE '<BACKEND_URL>/admin/reservations/<RESERVATION_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the reservation ID to be passed as a path parameter.
|
||||
This API Route requires the reservation ID to be passed as a path parameter.
|
||||
|
||||
The request returns the following fields:
|
||||
|
||||
- `id`: The ID of the reservation.
|
||||
- `object`: The type of object that was removed. In this case, the value will be `reservation`.
|
||||
- `object`: The type of object that was removed. In this case, the value will be `reservation`.
|
||||
- `deleted`: A boolean value indicating whether the reservation was successfully deleted.
|
||||
|
||||
---
|
||||
@@ -573,7 +573,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/fulfillment' \
|
||||
|
||||
The `location_id` is an optional parameter that allows you to specify where to fulfill the item from. This subsequently decrements the stock quantity of the product variant in that location.
|
||||
|
||||
You can learn more about this endpoint’s parameters and response in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillments).
|
||||
You can learn more about this API Route's parameters and response in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillments).
|
||||
|
||||
---
|
||||
|
||||
@@ -679,7 +679,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/return' \
|
||||
|
||||
The `location_id` is an optional parameter that allows you to specify where to return the item to. This subsequently increments the stock quantity of the product variant in that location.
|
||||
|
||||
You can learn more about this endpoint’s parameters and response in [the API reference](https://docs.medusajs.com/api/admin#orders_postordersorderreturns).
|
||||
You can learn more about this API Route's parameters and response in [the API reference](https://docs.medusajs.com/api/admin#orders_postordersorderreturns).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ You want to add or use the following admin functionalities:
|
||||
|
||||
:::note
|
||||
|
||||
You can check the [API reference](https://docs.medusajs.com/api/admin) for all available Reservations endpoints.
|
||||
You can check the [API reference](https://docs.medusajs.com/api/admin) for all available Reservations API Routes.
|
||||
|
||||
:::
|
||||
|
||||
@@ -69,7 +69,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## List Reservations
|
||||
|
||||
You can list all reservations in your store by sending a request to the [List Reservations endpoint](https://docs.medusajs.com/api/admin#reservations_getreservations):
|
||||
You can list all reservations in your store by sending a request to the [List Reservations API Route](https://docs.medusajs.com/api/admin#reservations_getreservations):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -134,9 +134,9 @@ curl -L -X GET '<BACKEND_URL>/admin/reservations' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint does not require any query or path parameters. You can pass it query parameters for filtering or pagination purposes. Check out the [API reference](https://docs.medusajs.com/api/admin#reservations_getreservations) for a list of accepted query parameters.
|
||||
This API Route doesn't require any query or path parameters. You can pass it query parameters for filtering or pagination purposes. Check out the [API reference](https://docs.medusajs.com/api/admin#reservations_getreservations) for a list of accepted query parameters.
|
||||
|
||||
This endpoint returns an array of reservations along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination).
|
||||
This API Route returns an array of reservations along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination).
|
||||
|
||||
---
|
||||
|
||||
@@ -148,7 +148,7 @@ Before you create a reservation for a product variant, make sure you’ve create
|
||||
|
||||
:::
|
||||
|
||||
You can create a reservation by sending a request to the [Create Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_postreservations):
|
||||
You can create a reservation by sending a request to the [Create Reservation API Route](https://docs.medusajs.com/api/admin#reservations_postreservations):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -227,7 +227,7 @@ curl -L -X POST '<BACKEND_URL>/admin/reservations' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the following body parameters:
|
||||
This API Route requires the following body parameters:
|
||||
|
||||
- `location_id`: The ID of the location the reservation is created in.
|
||||
- `inventory_item_id`: The ID of the inventory item the product variant is associated with.
|
||||
@@ -239,7 +239,7 @@ The request returns the created reservation as an object.
|
||||
|
||||
## Update a Reservation
|
||||
|
||||
You can update a reservation by sending a request to the [Update Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_postreservationsreservation):
|
||||
You can update a reservation by sending a request to the [Update Reservation API Route](https://docs.medusajs.com/api/admin#reservations_postreservationsreservation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -312,7 +312,7 @@ curl -L -X POST '<BACKEND_URL>/admin/reservations/<RESERVATION_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of the reservation as a path parameter.
|
||||
This API Route requires the ID of the reservation as a path parameter.
|
||||
|
||||
In the request body parameters, you can optionally pass any of the following parameters to make updates to the reservation:
|
||||
|
||||
@@ -326,7 +326,7 @@ The request returns the updated reservation as an object.
|
||||
|
||||
## Delete a Reservation
|
||||
|
||||
You can delete a reservation by sending a request to the [Delete Reservation endpoint](https://docs.medusajs.com/api/admin#reservations_deletereservationsreservation):
|
||||
You can delete a reservation by sending a request to the [Delete Reservation API Route](https://docs.medusajs.com/api/admin#reservations_deletereservationsreservation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -385,7 +385,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/reservations/<RESERVATION_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the reservation ID to be passed as a path parameter.
|
||||
This API Route requires the reservation ID to be passed as a path parameter.
|
||||
|
||||
The request returns the following fields:
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## List Stock Locations
|
||||
|
||||
You can list stock locations by using the [List Stock Locations endpoint](https://docs.medusajs.com/api/admin#stock-locations_getstocklocations):
|
||||
You can list stock locations by using the [List Stock Locations API Route](https://docs.medusajs.com/api/admin#stock-locations_getstocklocations):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -128,7 +128,7 @@ curl -L -X GET '<BACKEND_URL>/admin/stock-locations' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint does not require any path or query parameters. You can, however, pass it query parameters to search or filter the list of stock locations. For example, you can pass the `q` query parameter to search through the locations by name. You can learn about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_getstocklocations).
|
||||
This API Route doesn't require any path or query parameters. You can, however, pass it query parameters to search or filter the list of stock locations. For example, you can pass the `q` query parameter to search through the locations by name. You can learn about available query parameters in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_getstocklocations).
|
||||
|
||||
The request returns an array of stock location objects along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination).
|
||||
|
||||
@@ -136,7 +136,7 @@ The request returns an array of stock location objects along with [pagination pa
|
||||
|
||||
## Create a Stock Location
|
||||
|
||||
You can create a stock location using the [Create a Stock Location endpoint](https://docs.medusajs.com/api/admin#stock-locations_poststocklocations):
|
||||
You can create a stock location using the [Create a Stock Location API Route](https://docs.medusajs.com/api/admin#stock-locations_poststocklocations):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -207,7 +207,7 @@ curl -L -X POST '<BACKEND_URL>/admin/stock-locations' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires in its body parameters the `name` field, which is the name of the stock location. You can also pass in the request body parameters other fields related to the address or metadata. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_poststocklocations).
|
||||
This API Route requires in its body parameters the `name` field, which is the name of the stock location. You can also pass in the request body parameters other fields related to the address or metadata. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_poststocklocations).
|
||||
|
||||
This request returns the created stock location as an object.
|
||||
|
||||
@@ -215,7 +215,7 @@ This request returns the created stock location as an object.
|
||||
|
||||
## Retrieve a Stock Location
|
||||
|
||||
You can retrieve a stock location by sending a request to the [Get Stock Location endpoint](https://docs.medusajs.com/api/admin#stock-locations_getstocklocationsstocklocation):
|
||||
You can retrieve a stock location by sending a request to the [Get Stock Location API Route](https://docs.medusajs.com/api/admin#stock-locations_getstocklocationsstocklocation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -277,7 +277,7 @@ curl -L -X GET '<BACKEND_URL>/admin/stock-locations/<LOC_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the stock location ID to be passed as a path parameter. It also accepts query parameters related to expanding and selecting fields. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_getstocklocationsstocklocation).
|
||||
This API Route requires the stock location ID to be passed as a path parameter. It also accepts query parameters related to expanding and selecting fields. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_getstocklocationsstocklocation).
|
||||
|
||||
It returns the stock location as an object.
|
||||
|
||||
@@ -285,7 +285,7 @@ It returns the stock location as an object.
|
||||
|
||||
## Associate a Stock Location with a Sales Channel
|
||||
|
||||
You can associate a stock location with a sales channel by sending a request to the [Associate Stock Channel endpoint](https://docs.medusajs.com/api/admin#sales-channels_postsaleschannelssaleschannelstocklocation):
|
||||
You can associate a stock location with a sales channel by sending a request to the [Associate Stock Channel API Route](https://docs.medusajs.com/api/admin#sales-channels_postsaleschannelssaleschannelstocklocation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -357,7 +357,7 @@ curl -L -X POST '<BACKEND_URL>/admin/sales-channels/<CHANNEL_ID>/stock-locations
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of the sales channel as a path parameter. In its body parameters, it requires the ID of the stock location you’re associating the sales channel with.
|
||||
This API Route requires the ID of the sales channel as a path parameter. In its body parameters, it requires the ID of the stock location you’re associating the sales channel with.
|
||||
|
||||
This request returns the sales channel object.
|
||||
|
||||
@@ -371,7 +371,7 @@ You can associate a location with more than one sales channel, and you can assoc
|
||||
|
||||
## Remove Association Between Stock Location and Sales Channel
|
||||
|
||||
You can remove the association between a stock location and a sales channel by sending a request to the [Remove Stock Location Association endpoint](https://docs.medusajs.com/api/admin#sales-channels_deletesaleschannelssaleschannelstocklocation):
|
||||
You can remove the association between a stock location and a sales channel by sending a request to the [Remove Stock Location Association API Route](https://docs.medusajs.com/api/admin#sales-channels_deletesaleschannelssaleschannelstocklocation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -446,7 +446,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/sales-channels/<CHANNEL_ID>/stock-locatio
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of the sales channel as a path parameter. In its body parameters, it requires the ID of the stock location you’re removing the association of the sales channel with.
|
||||
This API Route requires the ID of the sales channel as a path parameter. In its body parameters, it requires the ID of the stock location you’re removing the association of the sales channel with.
|
||||
|
||||
The request returns the following fields:
|
||||
|
||||
@@ -464,7 +464,7 @@ This request does not delete the stock location. It only removes the association
|
||||
|
||||
## Update a Stock Location
|
||||
|
||||
You can update a stock location by sending a request to the [Update Stock Location endpoint](https://docs.medusajs.com/api/admin#stock-locations_poststocklocationsstocklocation):
|
||||
You can update a stock location by sending a request to the [Update Stock Location API Route](https://docs.medusajs.com/api/admin#stock-locations_poststocklocationsstocklocation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -537,7 +537,7 @@ curl -L -X POST '<BACKEND_URL>/admin/stock-locations/<LOC_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of a stock location as a path parameter. In its body parameters, you can pass any of the location’s attributes to update, such as the name or address. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_poststocklocationsstocklocation).
|
||||
This API Route requires the ID of a stock location as a path parameter. In its body parameters, you can pass any of the location’s attributes to update, such as the name or address. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#stock-locations_poststocklocationsstocklocation).
|
||||
|
||||
This request returns the updated stock location as an object.
|
||||
|
||||
@@ -545,7 +545,7 @@ This request returns the updated stock location as an object.
|
||||
|
||||
## Delete a Stock Location
|
||||
|
||||
You can delete a stock location by sending a request to the [Delete Stock Location endpoint](https://docs.medusajs.com/api/admin#stock-locations_deletestocklocationsstocklocation):
|
||||
You can delete a stock location by sending a request to the [Delete Stock Location API Route](https://docs.medusajs.com/api/admin#stock-locations_deletestocklocationsstocklocation):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -604,7 +604,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/stock-locations/<LOC_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of the stock location as a path parameter.
|
||||
This API Route requires the ID of the stock location as a path parameter.
|
||||
|
||||
It returns the following fields in the response:
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ This guide will only explain what is required to create in your custom inventory
|
||||
|
||||
:::note
|
||||
|
||||
It should be noted that the Medusa backend expects the inventory module to have entities for an inventory item, an inventory level, and a reservation item, as it uses the IDs of those entities when orchestrating between different modules and the in the endpoints it exposes. You can learn more about this in the [Inventory Module Architecture documentation](../inventory-module.md).
|
||||
It should be noted that the Medusa backend expects the inventory module to have entities for an inventory item, an inventory level, and a reservation item, as it uses the IDs of those entities when orchestrating between different modules and the in the API Routes it exposes. You can learn more about this in the [Inventory Module Architecture documentation](../inventory-module.md).
|
||||
|
||||
:::
|
||||
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ This guide will only explain what is required to create in your custom stock loc
|
||||
|
||||
:::note
|
||||
|
||||
It should be noted that the Medusa backend expects the stock location module to have entities for a location and a location address, as it uses the IDs of those entities when orchestrating between different modules and the in the endpoints it exposes. You can learn more about this in the [Stock Location Module Architecture documentation](../stock-location-module.md).
|
||||
It should be noted that the Medusa backend expects the stock location module to have entities for a location and a location address, as it uses the IDs of those entities when orchestrating between different modules and the in the API Routes it exposes. You can learn more about this in the [Stock Location Module Architecture documentation](../stock-location-module.md).
|
||||
|
||||
:::
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import TabItem from '@theme/TabItem';
|
||||
|
||||
# How to Edit an Order
|
||||
|
||||
In this document, you’ll learn how to create an order edit using the Admin API endpoints.
|
||||
In this document, you’ll learn how to create an order edit using the Admin API Routes.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -80,7 +80,7 @@ You must have an existing order that you want to edit.
|
||||
|
||||
Before you can start making changes to an order, you have to create a new order edit.
|
||||
|
||||
To do that, send a request to the [Create an OrderEdit](https://docs.medusajs.com/api/admin#order-edits_postorderedits) endpoint:
|
||||
To do that, send a request to the [Create an OrderEdit API Route](https://docs.medusajs.com/api/admin#order-edits_postorderedits):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -150,7 +150,7 @@ curl -L -X POST '<BACKEND_URL>/admin/order-edits' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint has one required request body parameter `order_id` which is the ID of the order this edit is being created for.
|
||||
This API Route has one required request body parameter `order_id` which is the ID of the order this edit is being created for.
|
||||
|
||||
This request returns the Order Edit under the `order_edit` property.
|
||||
|
||||
@@ -174,7 +174,7 @@ You can only make changes to items that have not been fulfilled yet in the order
|
||||
|
||||
### Add an Item
|
||||
|
||||
To add a new item to the original order, send a request to the [Add Line Item](https://docs.medusajs.com/api/admin#order-edits_postordereditseditlineitems) endpoint:
|
||||
To add a new item to the original order, send a request to the [Add Line Item API Route](https://docs.medusajs.com/api/admin#order-edits_postordereditseditlineitems):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -259,7 +259,7 @@ This request returns the Order Edit object. You can access returned item changes
|
||||
|
||||
You can edit an item’s quantity in the original order.
|
||||
|
||||
To update an item, send a request to the [Update Line Item](https://docs.medusajs.com/api/admin#order-edits_postordereditseditlineitemslineitem) endpoint:
|
||||
To update an item, send a request to the [Update Line Item API Route](https://docs.medusajs.com/api/admin#order-edits_postordereditseditlineitemslineitem):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -342,7 +342,7 @@ This request returns the Order Edit object. You can access returned item changes
|
||||
|
||||
### Remove an Item
|
||||
|
||||
You can remove an item from the original order by sending a request to the [Remove Line Item](https://docs.medusajs.com/api/admin#order-edits_deleteordereditsordereditlineitemslineitem) endpoint:
|
||||
You can remove an item from the original order by sending a request to the [Remove Line Item API Route](https://docs.medusajs.com/api/admin#order-edits_deleteordereditsordereditlineitemslineitem):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -413,7 +413,7 @@ This request returns the Order Edit object. You can access returned item changes
|
||||
|
||||
A merchant might make a mistake while making a change to the original order’s items. Using the Admin API, you can revert item changes previously created.
|
||||
|
||||
To revert an item change, send a request to the [Delete Item Change](https://docs.medusajs.com/api/admin#order-edits_deleteordereditsorderedititemchange) endpoint:
|
||||
To revert an item change, send a request to the [Delete Item Change API Route](https://docs.medusajs.com/api/admin#order-edits_deleteordereditsorderedititemchange):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -491,7 +491,7 @@ This request returns an object with the following properties:
|
||||
|
||||
After an Order Edit is created and all the item changes are added, it must be moved into the request state.
|
||||
|
||||
To move an Order Edit into the request state, send a request to the [Request Confirmation](https://docs.medusajs.com/api/admin#order-edits_postordereditsordereditrequest) endpoint:
|
||||
To move an Order Edit into the request state, send a request to the [Request Confirmation API Route](https://docs.medusajs.com/api/admin#order-edits_postordereditsordereditrequest):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -587,7 +587,7 @@ When the merchant force-confirms the order edit, however, it bypasses the paymen
|
||||
|
||||
This section covers how the Admin API can be used to force-confirm the Order Edit. You can refer to [this documentation to learn how to implement Order Edit confirmation on the storefront](../storefront/handle-order-edits.mdx).
|
||||
|
||||
To confirm an Order Edit, send a request to the [Confirm Order Edit](https://docs.medusajs.com/api/admin#order-edits_postordereditsordereditconfirm) endpoint:
|
||||
To confirm an Order Edit, send a request to the [Confirm Order Edit API Route](https://docs.medusajs.com/api/admin#order-edits_postordereditsordereditconfirm):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -670,7 +670,7 @@ You can learn how to allow customers to authorize payment on the storefront in [
|
||||
|
||||
### Capture Payment
|
||||
|
||||
If the payment is authorized by the customer, it can be captured by sending a request to the [Capture Payment](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentcapture) endpoint:
|
||||
If the payment is authorized by the customer, it can be captured by sending a request to the [Capture Payment API Route](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentcapture):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -736,7 +736,7 @@ It returns in the response the full Payment object.
|
||||
|
||||
When the total after the order edit is less than the original order total, the merchant can refund the difference to the customer.
|
||||
|
||||
To refund the difference to the customer, send a request to the [Refund Payment](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentrefunds) endpoint:
|
||||
To refund the difference to the customer, send a request to the [Refund Payment API Route](https://docs.medusajs.com/api/admin#payments_postpaymentspaymentrefunds):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
|
||||
@@ -58,7 +58,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## View Order’s Claims
|
||||
|
||||
To view an order’s claims, you can retrieve the order using the [Get Order endpoint](https://docs.medusajs.com/api/admin#orders_getordersorder) and access the order’s claims:
|
||||
To view an order’s claims, you can retrieve the order using the [Get Order API Route](https://docs.medusajs.com/api/admin#orders_getordersorder) and access the order’s claims:
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -137,7 +137,7 @@ The request returns the order as an object. In that object, you can access an ar
|
||||
|
||||
## Create Claim
|
||||
|
||||
You can create a claim by sending a request to the [Create Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaims):
|
||||
You can create a claim by sending a request to the [Create Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaims):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -232,7 +232,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/claims' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order ID to be passed as a path parameter.
|
||||
This API Route requires the order ID to be passed as a path parameter.
|
||||
|
||||
In the request body, the following parameters are required:
|
||||
|
||||
@@ -255,7 +255,7 @@ The request returns the updated order as an object. You can access the order’s
|
||||
|
||||
## Update a Claim
|
||||
|
||||
You can update a claim by sending a request to the [Update Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaim):
|
||||
You can update a claim by sending a request to the [Update Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaim):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -330,7 +330,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/claims/<CLAIM_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of the order and the claim to be passed as path parameters.
|
||||
This API Route requires the ID of the order and the claim to be passed as path parameters.
|
||||
|
||||
In the request body, you can pass any of the claim’s fields that you want to update as parameters. In the example above, the `no_notification` field is updated.
|
||||
|
||||
@@ -346,7 +346,7 @@ Fulfillments are available on a claim object under the `fulfillments` property,
|
||||
|
||||
### Create Fulfillment
|
||||
|
||||
You can create a fulfillment for a claim by sending a request to the [Create Claim Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimfulfillments):
|
||||
You can create a fulfillment for a claim by sending a request to the [Create Claim Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimfulfillments):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -408,7 +408,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/claims/<CLAIM_ID>/fulfill
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order and claim IDs as path parameters.
|
||||
This API Route requires the order and claim IDs as path parameters.
|
||||
|
||||
In the request body, you can pass optional parameters such as `metadata` or `no_notification`. These parameters will be used to create the fulfillment. You can learn more about available request body parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimfulfillments).
|
||||
|
||||
@@ -416,7 +416,7 @@ The request returns the updated order as an object. You can access the order’s
|
||||
|
||||
### Create a Shipment
|
||||
|
||||
You can create a shipment for a claim by sending a request to the [Create Claim Shipment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimshipments):
|
||||
You can create a shipment for a claim by sending a request to the [Create Claim Shipment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimshipments):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -490,7 +490,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/claims/<CLAIM_ID>/shipmen
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order and claim IDs as path parameters.
|
||||
This API Route requires the order and claim IDs as path parameters.
|
||||
|
||||
In the request body, it’s required to pass the `fulfillment_id` parameter, which is the ID of the fulfillment the shipment is being created for. You can pass other optional parameters, such as an array of tracking numbers. You can learn more in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorderclaimsclaimshipments).
|
||||
|
||||
@@ -508,7 +508,7 @@ You can’t cancel a fulfillment that has a shipment
|
||||
|
||||
:::
|
||||
|
||||
You can cancel a fulfillment by sending a request to the [Cancel Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersclaimfulfillmentscancel):
|
||||
You can cancel a fulfillment by sending a request to the [Cancel Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersclaimfulfillmentscancel):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -576,7 +576,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/claims/<CLAIM_ID>/fulfill
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order, claim, and fulfillment IDs to be passed as path parameters.
|
||||
This API Route requires the order, claim, and fulfillment IDs to be passed as path parameters.
|
||||
|
||||
The request returns the updated order as an object. You can access the claims using the `claims` property of the order object, which is an array of claim objects.
|
||||
|
||||
@@ -592,7 +592,7 @@ You can’t cancel a claim that has been refunded. You must also cancel the clai
|
||||
|
||||
:::
|
||||
|
||||
You can cancel a claim by sending a request to the [Cancel Claim endpoint](https://docs.medusajs.com/api/admin#orders_postordersclaimcancel):
|
||||
You can cancel a claim by sending a request to the [Cancel Claim API Route](https://docs.medusajs.com/api/admin#orders_postordersclaimcancel):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -651,7 +651,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/claims/<CLAIM_ID>/cancel'
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order and claim IDs as path parameters.
|
||||
This API Route requires the order and claim IDs as path parameters.
|
||||
|
||||
The request returns the updated order as an object. You can access the claims using the `claims` property of the order object, which is an array of claim objects.
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## List Draft Orders
|
||||
|
||||
You can list draft orders by sending a request to the [List Draft Orders endpoint](https://docs.medusajs.com/api/admin#draft-orders_getdraftorders):
|
||||
You can list draft orders by sending a request to the [List Draft Orders API Route](https://docs.medusajs.com/api/admin#draft-orders_getdraftorders):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -117,7 +117,7 @@ curl -L -X GET '<BACKEND_URL>/admin/draft-orders' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint does not require any path or query parameters. You can pass search or pagination query parameters as explained in the [API reference](https://docs.medusajs.com/api/admin#draft-orders_getdraftorders).
|
||||
This API Route doesn't require any path or query parameters. You can pass search or pagination query parameters as explained in the [API reference](https://docs.medusajs.com/api/admin#draft-orders_getdraftorders).
|
||||
|
||||
The request returns an array of draft order objects along with [pagination parameters](https://docs.medusajs.com/api/admin#pagination).
|
||||
|
||||
@@ -125,7 +125,7 @@ The request returns an array of draft order objects along with [pagination param
|
||||
|
||||
## Create a Draft Order
|
||||
|
||||
You can create a draft order by sending a request to the [Create Draft Order endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftorders):
|
||||
You can create a draft order by sending a request to the [Create Draft Order API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftorders):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -277,7 +277,7 @@ curl -L -X POST '<BACKEND_URL>/admin/draft-orders' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the following request body parameters:
|
||||
This API Route requires the following request body parameters:
|
||||
|
||||
- `email`: a string indicating the email of the customer to associate this draft order with.
|
||||
- `region_id`: a string indicating the ID of the region this draft order belongs to.
|
||||
@@ -298,7 +298,7 @@ The request returns the created draft order as an object.
|
||||
|
||||
## Retrieve Draft Order
|
||||
|
||||
You can retrieve a draft order by sending a request to the [Get Draft Order endpoint](https://docs.medusajs.com/api/admin#draft-orders_getdraftordersdraftorder):
|
||||
You can retrieve a draft order by sending a request to the [Get Draft Order API Route](https://docs.medusajs.com/api/admin#draft-orders_getdraftordersdraftorder):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -358,7 +358,7 @@ curl -L -X GET '<BACKEND_URL>/admin/draft-orders/<DRAFT_ORDER_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the draft order’s ID as a path parameter.
|
||||
This API Route requires the draft order’s ID as a path parameter.
|
||||
|
||||
The request returns the draft order as an object.
|
||||
|
||||
@@ -366,7 +366,7 @@ The request returns the draft order as an object.
|
||||
|
||||
## Update Draft Order
|
||||
|
||||
You can update a draft order by sending a request to the [Update Draft Order endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorder):
|
||||
You can update a draft order by sending a request to the [Update Draft Order API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorder):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -439,7 +439,7 @@ curl -L -X POST '<BACKEND_URL>/admin/draft-orders/<DRAFT_ORDER_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the draft order’s ID as a path parameter.
|
||||
This API Route requires the draft order’s ID as a path parameter.
|
||||
|
||||
In the request body, you can pass any of the draft order’s fields to update. In the example above, you update the `email` field. Check out the [API reference](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorder) to learn about other accepted request body parameters.
|
||||
|
||||
@@ -451,7 +451,7 @@ The request returns the updated draft order as an object.
|
||||
|
||||
### Add Line Items
|
||||
|
||||
You can add line items to a draft order by sending a request to the [Create Line Items endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitems):
|
||||
You can add line items to a draft order by sending a request to the [Create Line Items API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitems):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -526,7 +526,7 @@ curl -L -X POST '<BACKEND_URL>/admin/draft-orders/<DRAFT_ORDER_ID>/line-items' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the ID of the draft order as a path parameter.
|
||||
This API Route requires the ID of the draft order as a path parameter.
|
||||
|
||||
In the request body, it’s required to pass the `quantity` parameter, which is a number indicating the quantity of the item in the draft order. You can also pass other optional parameters based on the type of line item you’re adding.
|
||||
|
||||
@@ -541,7 +541,7 @@ The request returns the updated draft order as an object. You can access the dra
|
||||
|
||||
### Update Line Item
|
||||
|
||||
You can update a line item by sending a request to the [Update Line Item endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitemsitem):
|
||||
You can update a line item by sending a request to the [Update Line Item API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitemsitem):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -617,7 +617,7 @@ curl -L -X POST '<BACKEND_URL>/admin/draft-orders/<DRAFT_ORDER_ID>/line-items/<I
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the draft order and line item’s IDs as path parameters.
|
||||
This API Route requires the draft order and line item’s IDs as path parameters.
|
||||
|
||||
In the request body, you can pass any of the line item’s fields as parameters to update them. In the example above, you pass the `quantity` parameter to update the quantity of the item. Check out the [API reference](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderlineitemsitem) for a full list of request body parameters.
|
||||
|
||||
@@ -625,7 +625,7 @@ The request returns the updated draft order as an object. You can access the dra
|
||||
|
||||
### Delete Line Item
|
||||
|
||||
You can delete a line item by sending a request to the [Delete Line Item endpoint](https://docs.medusajs.com/api/admin#draft-orders_deletedraftordersdraftorderlineitemsitem):
|
||||
You can delete a line item by sending a request to the [Delete Line Item API Route](https://docs.medusajs.com/api/admin#draft-orders_deletedraftordersdraftorderlineitemsitem):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -686,7 +686,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/draft-orders/<DRAFT_ORDER_ID>/line-items/
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the draft order and line item’s IDs as path parameters.
|
||||
This API Route requires the draft order and line item’s IDs as path parameters.
|
||||
|
||||
The request returns the updated draft order as an object. You can access the draft order’s items by accessing the `carts` property in the draft item, then the `items` property. The `items` property is an array of line item objects.
|
||||
|
||||
@@ -696,7 +696,7 @@ The request returns the updated draft order as an object. You can access the dra
|
||||
|
||||
Registering the draft order’s payment leads to authorizing and capturing the payment using the `system` payment method. This would complete the draft order and create an order from it.
|
||||
|
||||
You can register the draft order payment by sending a request to the [Register Draft Order Payment endpoint](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderregisterpayment):
|
||||
You can register the draft order payment by sending a request to the [Register Draft Order Payment API Route](https://docs.medusajs.com/api/admin#draft-orders_postdraftordersdraftorderregisterpayment):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -755,7 +755,7 @@ curl -L -X POST '<BACKEND_URL>/admin/draft-orders/<DRAFT_ORDER_ID>/pay' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the draft order’s ID as a path parameter.
|
||||
This API Route requires the draft order’s ID as a path parameter.
|
||||
|
||||
The request returns the order created from the draft order as an object.
|
||||
|
||||
@@ -763,7 +763,7 @@ The request returns the order created from the draft order as an object.
|
||||
|
||||
## Delete a Draft Order
|
||||
|
||||
You can delete a draft order by sending a request to the [Delete Draft Order endpoint](https://docs.medusajs.com/api/admin#draft-orders_deletedraftordersdraftorder):
|
||||
You can delete a draft order by sending a request to the [Delete Draft Order API Route](https://docs.medusajs.com/api/admin#draft-orders_deletedraftordersdraftorder):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -822,7 +822,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/draft-orders/<DRAFT_ORDER_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the draft order’s ID as a path parameter.
|
||||
This API Route requires the draft order’s ID as a path parameter.
|
||||
|
||||
The request returns the following fields:
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ You can learn more about [authenticating as an admin user in the API reference](
|
||||
|
||||
## List Orders
|
||||
|
||||
You can list orders by sending a request to the [List Orders endpoint](https://docs.medusajs.com/api/admin#orders_getorders):
|
||||
You can list orders by sending a request to the [List Orders API Route](https://docs.medusajs.com/api/admin#orders_getorders):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -123,13 +123,13 @@ curl -L -X GET '<BACKEND_URL>/admin/orders' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint does not require any path parameters. You can pass it query parameters to filter the orders received.
|
||||
This API Route doesn't require any path parameters. You can pass it query parameters to filter the orders received.
|
||||
|
||||
The request returns an array of orders along with [pagination fields](https://docs.medusajs.com/api/admin#pagination).
|
||||
|
||||
### Filter Orders
|
||||
|
||||
This endpoint accepts a variety of query parameters that allow you to filter orders. You can check available query parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_getorders).
|
||||
This API Route accepts a variety of query parameters that allow you to filter orders. You can check available query parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_getorders).
|
||||
|
||||
For example, you can filter the orders by one or more status:
|
||||
|
||||
@@ -380,7 +380,7 @@ curl -L -X GET '<BACKEND_URL>/admin/orders?status[]=completed&sales_channel_id[]
|
||||
|
||||
## Retrieve an Order
|
||||
|
||||
You can retrieve an order by sending a request to the [Get an Order endpoint](https://docs.medusajs.com/api/admin#orders_getordersorder):
|
||||
You can retrieve an order by sending a request to the [Get an Order API Route](https://docs.medusajs.com/api/admin#orders_getordersorder):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -440,7 +440,7 @@ curl -L -X GET '<BACKEND_URL>/admin/orders/<ORDER_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order ID to be passed as a path parameter.
|
||||
This API Route requires the order ID to be passed as a path parameter.
|
||||
|
||||
The request returns the full order as an object.
|
||||
|
||||
@@ -461,7 +461,7 @@ Updating an order’s details can include updating its:
|
||||
- Shipping Method
|
||||
- `no_notification` property
|
||||
|
||||
You can update any of the above details of an order by sending a request to the [Update an Order endpoint](https://docs.medusajs.com/api/admin#orders_postordersorder):
|
||||
You can update any of the above details of an order by sending a request to the [Update an Order API Route](https://docs.medusajs.com/api/admin#orders_postordersorder):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -534,7 +534,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order’s ID to be passed as a path parameter.
|
||||
This API Route requires the order’s ID to be passed as a path parameter.
|
||||
|
||||
In the request body parameters, you can pass any of the order’s fields mentioned earlier that you want to update. In the example above, you edit the email associated with the order. You can learn about other available request body parameters in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersorder).
|
||||
|
||||
@@ -546,7 +546,7 @@ The request returns the updated order as an object.
|
||||
|
||||
### Capture an Order’s Payment
|
||||
|
||||
You can capture an order’s payment by sending a request to the [Capture Order’s Payment endpoint](https://docs.medusajs.com/api/admin#orders_postordersordercapture):
|
||||
You can capture an order’s payment by sending a request to the [Capture Order’s Payment API Route](https://docs.medusajs.com/api/admin#orders_postordersordercapture):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -606,7 +606,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/capture' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the Order ID as a path parameter.
|
||||
This API Route requires the Order ID as a path parameter.
|
||||
|
||||
The request returns the updated order as an object.
|
||||
|
||||
@@ -614,7 +614,7 @@ The request returns the updated order as an object.
|
||||
|
||||
You can refund an amount that is less than `order.refundable_amount`.
|
||||
|
||||
To refund payment, send a request to the [Refund Payment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderrefunds):
|
||||
To refund payment, send a request to the [Refund Payment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderrefunds):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -691,7 +691,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/refund' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order’s ID to be passed as a path parameter.
|
||||
This API Route requires the order’s ID to be passed as a path parameter.
|
||||
|
||||
The following parameters are required in the request body parameters:
|
||||
|
||||
@@ -708,7 +708,7 @@ The request returns the updated order as an object.
|
||||
|
||||
### Create a Fulfillment
|
||||
|
||||
You can create a fulfillment by sending a request to the [Create a Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillments):
|
||||
You can create a fulfillment by sending a request to the [Create a Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillments):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -801,7 +801,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/fulfillment' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order’s ID to be passed as a path parameter.
|
||||
This API Route requires the order’s ID to be passed as a path parameter.
|
||||
|
||||
In the request body, the `items` parameter is required. It’s an array of objects that are the items to fulfill. You can fulfill all items in the order or some items.
|
||||
|
||||
@@ -816,7 +816,7 @@ The request returns the updated order as an object.
|
||||
|
||||
### Create Shipment
|
||||
|
||||
You can create a shipment for a fulfillment by sending a request to the [Create Shipment endpoint](https://docs.medusajs.com/api/admin#orders_postordersordershipment):
|
||||
You can create a shipment for a fulfillment by sending a request to the [Create Shipment API Route](https://docs.medusajs.com/api/admin#orders_postordersordershipment):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -889,7 +889,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/shipment' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires passing the order’s ID as a path parameter.
|
||||
This API Route requires passing the order’s ID as a path parameter.
|
||||
|
||||
In the request body, the `fulfillment_id` parameter is required. Its value is the ID of the fulfillment to create the shipment for. You can also pass other optional body parameters as explained in the [API reference](https://docs.medusajs.com/api/admin#orders_postordersordershipment).
|
||||
|
||||
@@ -897,7 +897,7 @@ The request returns the updated order as an object.
|
||||
|
||||
### Cancel Fulfillment
|
||||
|
||||
You can cancel a fulfillment by sending a request to the [Cancel Fulfillment endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillmentscancel):
|
||||
You can cancel a fulfillment by sending a request to the [Cancel Fulfillment API Route](https://docs.medusajs.com/api/admin#orders_postordersorderfulfillmentscancel):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -958,7 +958,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/fulfillments/<FUL_ID>/can
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires passing the order’s ID and fulfillment ID as path parameters.
|
||||
This API Route requires passing the order’s ID and fulfillment ID as path parameters.
|
||||
|
||||
The request returns the updated order as an object.
|
||||
|
||||
@@ -966,7 +966,7 @@ The request returns the updated order as an object.
|
||||
|
||||
## Completing an Order
|
||||
|
||||
You can mark an order completed, changing its status, by sending a request to the [Complete an Order endpoint](https://docs.medusajs.com/api/admin#orders_postordersordercomplete):
|
||||
You can mark an order completed, changing its status, by sending a request to the [Complete an Order API Route](https://docs.medusajs.com/api/admin#orders_postordersordercomplete):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -1025,7 +1025,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/complete' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order ID to be passed as a path parameter.
|
||||
This API Route requires the order ID to be passed as a path parameter.
|
||||
|
||||
The request returns the updated order as an object.
|
||||
|
||||
@@ -1033,7 +1033,7 @@ The request returns the updated order as an object.
|
||||
|
||||
## Cancel an Order
|
||||
|
||||
You can cancel an order by sending a request to the [Cancel Order endpoint](https://docs.medusajs.com/api/admin#orders_postordersordercancel):
|
||||
You can cancel an order by sending a request to the [Cancel Order API Route](https://docs.medusajs.com/api/admin#orders_postordersordercancel):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -1092,7 +1092,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/cancel' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order ID to be passed as a path parameter.
|
||||
This API Route requires the order ID to be passed as a path parameter.
|
||||
|
||||
The request returns the updated order as an object.
|
||||
|
||||
@@ -1100,7 +1100,7 @@ The request returns the updated order as an object.
|
||||
|
||||
## Archive Order
|
||||
|
||||
You can archive an order by sending a request to the [Archive Order endpoint](https://docs.medusajs.com/api/admin#orders_postordersorderarchive):
|
||||
You can archive an order by sending a request to the [Archive Order API Route](https://docs.medusajs.com/api/admin#orders_postordersorderarchive):
|
||||
|
||||
<Tabs groupId="request-type" isCodeTabs={true}>
|
||||
<TabItem value="client" label="Medusa JS Client" default>
|
||||
@@ -1159,7 +1159,7 @@ curl -L -X POST '<BACKEND_URL>/admin/orders/<ORDER_ID>/archive' \
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
This endpoint requires the order ID to be passed as a path parameter.
|
||||
This API Route requires the order ID to be passed as a path parameter.
|
||||
|
||||
The request returns the updated order as an object.
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user