### Run Node.js Example with ts-node Source: https://github.com/hendt/ebay-api/blob/master/examples/README.md Execute a TypeScript example file using ts-node. Ensure Node.js and ts-node are installed. ```bash ts-node examples/restful/buy/items.getItem.ts ``` -------------------------------- ### Install eBay API Library Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/INDEX.md Install the eBay API library using npm. ```bash npm install ebay-api ``` -------------------------------- ### Complete eBay API Configuration Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/configuration.md A comprehensive example demonstrating how to configure the eBay API client with credentials, environment settings, language preferences, OAuth scopes, digital signature details, and request/HTTP client options. ```typescript import eBayApi from 'ebay-api'; const eBay = new eBayApi({ // Credentials appId: process.env.EBAY_APP_ID, certId: process.env.EBAY_CERT_ID, devId: process.env.EBAY_DEV_ID, // Environment sandbox: false, siteId: eBayApi.SiteId.EBAY_DE, marketplaceId: eBayApi.MarketplaceId.EBAY_DE, // Language & Localization contentLanguage: eBayApi.ContentLanguage.de_DE, acceptLanguage: eBayApi.Locale.de_DE, // OAuth ruName: 'https://my-app.example.com/oauth-callback', scope: [ 'https://api.ebay.com/oauth/api_scope', 'https://api.ebay.com/oauth/api_scope/sell.fulfillment' ], // Digital Signature (for EU/UK) signature: { jwe: process.env.EBAY_JWE, privateKey: process.env.EBAY_PRIVATE_KEY, cipher: 'sha256' }, // Request Options autoRefreshToken: true, // HTTP Client axiosConfig: { timeout: 30000, maxRedirects: 5 }, // XML Parser parseOptions: { processEntities: { maxTotalExpansions: 20000 } } }); // Set OAuth token eBay.OAuth2.setCredentials({ access_token: 'USER_ACCESS_TOKEN', refresh_token: 'REFRESH_TOKEN', expires_in: 7200 }); // Listen for token refresh eBay.OAuth2.on('refreshAuthToken', (token) => { // Save token to database db.saveToken(token); }); // Use API const orders = await eBay.sell.fulfillment.getOrders(); ``` -------------------------------- ### Quick Navigation - By Use Case Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/README.md Provides guidance on navigating the documentation based on common use cases, such as getting started, authentication, using specific APIs, or handling errors. ```APIDOC ## Quick Navigation - By Use Case Provides guidance on navigating the documentation based on common use cases, such as getting started, authentication, using specific APIs, or handling errors. ### Getting Started 1. Read [INDEX.md](./INDEX.md) for quick start 2. Review [configuration.md](./configuration.md) for setup options 3. Check [api-reference/eBayApi.md](./api-reference/eBayApi.md) for initialization ### OAuth Authentication 1. [api-reference/OAuth2.md](./api-reference/OAuth2.md) - Complete OAuth2 guide 2. [configuration.md](./configuration.md#oauth-scopes) - Scope reference 3. [errors.md](./errors.md) - Error handling for auth flows ### Traditional Trading API 1. [api-reference/TradingAPI.md](./api-reference/TradingAPI.md) - Trading API reference 2. [api-reference/AuthNAuth.md](./api-reference/AuthNAuth.md) - Auth'N'Auth flow 3. [configuration.md](./configuration.md#traditional-api-with-authnauth) - Configuration ### RESTful APIs 1. [api-reference/BuyBrowse.md](./api-reference/BuyBrowse.md) - Browse API example 2. [api-reference/SellAccount.md](./api-reference/SellAccount.md) - Account API example 3. [api-reference/Restful.md](./api-reference/Restful.md) - RESTful base class ### Error Handling 1. [errors.md](./errors.md) - Complete error reference 2. [api-reference/OAuth2.md](./api-reference/OAuth2.md#error-handling) - OAuth errors 3. [types.md](./types.md#error-types) - Error type definitions ### All Methods 1. [API_METHODS_REFERENCE.md](./API_METHODS_REFERENCE.md) - Complete method listing ``` -------------------------------- ### Install eBay Node API Source: https://github.com/hendt/ebay-api/blob/master/README.md Install the ebay-api package using npm or yarn. ```bash npm install ebay-api # or yarn add ebay-api ``` -------------------------------- ### Complete eBay Sell Account API Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/SellAccount.md A comprehensive example demonstrating initialization, authentication, and various operations including fetching and creating policies, retrieving seller privileges, and checking inventory locations. ```typescript import eBayApi from 'ebay-api'; const eBay = new eBayApi({ appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', sandbox: false }); // Set OAuth token eBay.OAuth2.setCredentials(userAccessToken); // Get current policies const fulfillmentPolicies = await eBay.sell.account.getFulfillmentPolicies('EBAY_US'); const paymentPolicies = await eBay.sell.account.getPaymentPolicies('EBAY_US'); const returnPolicies = await eBay.sell.account.getReturnPolicies('EBAY_US'); // Create new policies if needed if (!fulfillmentPolicies.fulfillmentPolicies?.some(p => p.name === 'Standard')) { const policyId = await eBay.sell.account.createFulfillmentPolicy({ name: 'Standard', shipToLocations: { regionIncluded: [{regionName: 'Americas'}], dispatchTimeMax: 1 } }); console.log('Created fulfillment policy:', policyId); } // Get seller privileges const privileges = await eBay.sell.account.getPrivileges(); console.log('Seller status:', { itemLimit: privileges.sellingLimits?.itemLimit, monthlyLimit: privileges.sellingLimits?.limitAmount }); // Get inventory locations const locations = await eBay.sell.account.getInventoryLocations(); console.log(`Inventory locations: ${locations.locations?.length}`); ``` -------------------------------- ### Example: Using getAccessToken Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/OAuth2.md Shows how to fetch an access token using the `getAccessToken` method and then use it for API requests, for example, by including it in custom request headers or storing it for future use. ```typescript const token = await eBay.OAuth2.getAccessToken(); // Use token in custom headers or store for later ``` -------------------------------- ### Complete eBay Trading API Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/TradingAPI.md A comprehensive example demonstrating initialization, fetching account details, listing items, and retrieving orders using the eBay Trading API. ```typescript import eBayApi from 'ebay-api'; const eBay = new eBayApi({ appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', devId: 'YOUR_DEV_ID', authToken: 'YOUR_AUTH_TOKEN', siteId: eBayApi.SiteId.EBAY_US, sandbox: false }); // Get account info const account = await eBay.trading.GetAccount(); console.log(`Seller feedback: ${account.User?.FeedbackScore}`); // Get active listings const selling = await eBay.trading.GetMyeBaySelling({ ActiveList: { Include: true, Pagination: {EntriesPerPage: 20, PageNumber: 1} } }); console.log(`Active listings: ${selling.ActiveListingCount}`); // Create new listing const itemResult = await eBay.trading.AddFixedPriceItem({ Item: { Title: 'Sample Item', Description: {__cdata: 'Item description'}, StartPrice: '19.99', ListingDuration: 'Days_30', Category2ID: '2984', ItemType: 'FixedPriceItem', Quantity: '5' } }); console.log(`Listed item: ${itemResult.ItemID}`); // Get order details const orders = await eBay.trading.GetOrders({ OrderStatus: 'Completed' }); orders.OrderArray?.Order?.forEach(order => { console.log(`Order ${order.OrderID}: ${order.Total?.value}`); }); ``` -------------------------------- ### RESTful Methods (Promises) Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Examples of how to call RESTful API methods using Promises, demonstrating GET, POST, PUT, and DELETE operations. ```APIDOC ## RESTful Methods (Promises) ### Description Examples of how to call RESTful API methods using Promises, demonstrating GET, POST, PUT, and DELETE operations. ### GET Request Example ```typescript const result = await eBay.buy.browse.search({q: 'iphone'}); ``` ### POST Request Example ```typescript const result = await eBay.sell.account.createFulfillmentPolicy({ name: 'Standard' }); ``` ### PUT Request Example ```typescript const result = await eBay.sell.account.updateFulfillmentPolicy( 'policy-id', {name: 'Updated'} ); ``` ### DELETE Request Example ```typescript const result = await eBay.sell.account.deleteFulfillmentPolicy('policy-id'); ``` ### Parameters Most RESTful methods accept: - `params` - Query string parameters (for GET) - `body` - Request body (for POST/PUT) - Optional final parameter for API configuration overrides ``` -------------------------------- ### Install zlib for JSON GZIP Response Handling Source: https://github.com/hendt/ebay-api/blob/master/README.md Install the zlib library to handle gzipped JSON responses from the eBay API. ```bash npm install zlib # or yarn add zlib ``` -------------------------------- ### Run Node.js Example with ESM Loader Source: https://github.com/hendt/ebay-api/blob/master/examples/README.md Execute a TypeScript example file using Node.js with the ts-node ESM loader. This is an alternative method for running TypeScript examples. ```bash node --loader ts-node/esm examples/restful/buy/items.getItem.ts ``` -------------------------------- ### GetAccount Method Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/TradingAPI.md Retrieves seller account information using the GetAccount method. This example logs the username, feedback score, and seller status from the response. ```typescript const account = await eBay.trading.GetAccount(); console.log('Account details:'); console.log(` Username: ${account.User?.UserID}`); console.log(` Feedback: ${account.User?.FeedbackScore}`); console.log(` Seller status: ${account.User?.SellerStatus}`); ``` -------------------------------- ### Get Base URL Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/Restful.md Demonstrates how to retrieve the full base URL for different API endpoints. Use this to construct request URLs. ```typescript console.log(browse.baseUrl); console.log(browse.apix.baseUrl); ``` -------------------------------- ### Complete Express.js OAuth2 Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/OAuth2.md A full Express.js application demonstrating the OAuth2 flow: initiating authentication, handling the callback, storing tokens, and making authenticated API requests. This example requires `express`, `express-session`, and `ebay-api`. ```typescript import express from 'express'; import session from 'express-session'; import eBayApi from 'ebay-api'; const app = express(); app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true })); const eBay = eBayApi.fromEnv(); // 1. Start OAuth flow app.get('/auth/ebay', (req, res) => { eBay.OAuth2.setScope([ 'https://api.ebay.com/oauth/api_scope', 'https://api.ebay.com/oauth/api_scope/sell.fulfillment' ]); const authUrl = eBay.OAuth2.generateAuthUrl(); res.redirect(authUrl); }); // 2. Handle OAuth callback app.get('/auth/ebay/callback', async (req, res) => { try { const token = await eBay.OAuth2.obtainToken(req.query.code); req.session.token = token; // Listen for token refreshes and save to database eBay.OAuth2.on('refreshAuthToken', (refreshedToken) => { req.session.token = refreshedToken; // Persist to database }); res.redirect('/dashboard'); } catch (error) { console.error('OAuth error:', error); res.status(400).send('Authentication failed'); } }); // 3. Use token in requests app.get('/api/orders', async (req, res) => { if (!req.session.token) { return res.status(403).json({error: 'Not authenticated'}); } const eBayWithToken = new eBayApi({...eBayApi.config}); eBayWithToken.OAuth2.setCredentials(req.session.token); const orders = await eBayWithToken.sell.fulfillment.getOrders(); res.json(orders); }); ``` -------------------------------- ### Example: Using Instance generateAuthUrl Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/OAuth2.md Demonstrates how to initialize the eBay API client and generate an authorization URL for user redirection. Sets custom scopes for the API access. ```typescript const eBay = new eBayApi({ appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', ruName: 'https://your-app.example.com/callback', sandbox: false }); eBay.OAuth2.setScope([ 'https://api.ebay.com/oauth/api_scope', 'https://api.ebay.com/oauth/api_scope/sell.fulfillment' ]); const url = eBay.OAuth2.generateAuthUrl(); console.log('Redirect user to:', url); ``` -------------------------------- ### Example: Using mintApplicationAccessToken Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/OAuth2.md Demonstrates how to mint a new application access token and log the received token and its expiration duration. This is useful for obtaining fresh credentials for API access. ```typescript const token = await eBay.OAuth2.mintApplicationAccessToken(); console.log('Token:', token.access_token); console.log('Expires in:', token.expires_in, 'seconds'); ``` -------------------------------- ### AddFixedPriceItem Method Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/TradingAPI.md Creates a fixed-price listing on eBay. This example demonstrates setting essential item properties such as title, description, price, duration, category, quantity, shipping, payment methods, and return policy. The ItemID of the newly created listing is logged upon success. ```typescript const result = await eBay.trading.AddFixedPriceItem({ Item: { Title: 'New iPhone 14 Pro', Description: { __cdata: '
Brand new, sealed box
' }, StartPrice: '999.99', ListingDuration: 'Days_30', Category2ID: '109200', ItemType: 'FixedPriceItem', Quantity: '1', ShippingDetails: { ShippingType: 'Flat', ShippingServiceOptions: { ShippingService: 'USPSPriority', ShippingServiceCost: '5.00' } }, PaymentMethods: 'PayPal', ReturnPolicy: { ReturnsAccepted: 'ReturnsAccepted', ReturnsWithinOption: 'Days_30', RefundOption: 'MoneyBack' } } }); console.log('Item listed:', result.ItemID); ``` -------------------------------- ### GetItem Method Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/TradingAPI.md Fetches details for a specific eBay item using its ItemID. This example includes optional parameters like IncludeWatchCount and DetailLevel, and logs the item's title, current price, bid count, and watch count. ```typescript const item = await eBay.trading.GetItem({ ItemID: '254188828753', IncludeWatchCount: true, DetailLevel: 'ReturnAll' }); console.log('Item details:'); console.log(` Title: ${item.Item?.Title}`); console.log(` Current price: ${item.Item?.CurrentPrice?.value}`); console.log(` Bids: ${item.Item?.BidCount}`); console.log(` Watch count: ${item.Item?.WatchCount}`); ``` -------------------------------- ### RESTful API Method Patterns Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Examples of common HTTP request methods (GET, POST, PUT, DELETE) used with RESTful eBay APIs. These methods are typically asynchronous and return Promises. ```typescript // GET request const result = await eBay.buy.browse.search({q: 'iphone'}); ``` ```typescript // POST request const result = await eBay.sell.account.createFulfillmentPolicy({ name: 'Standard' }); ``` ```typescript // PUT request const result = await eBay.sell.account.updateFulfillmentPolicy( 'policy-id', {name: 'Updated'} ); ``` ```typescript // DELETE request const result = await eBay.sell.account.deleteFulfillmentPolicy('policy-id'); ``` -------------------------------- ### Performing a GET Request Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/Restful.md Use the `get` method to perform HTTP GET requests. Pass the relative path and an optional Axios config object for parameters like query strings. ```typescript const items = await browse.get('/item_summary/search', { params: { q: 'iphone', limit: 50 } }); ``` -------------------------------- ### Type-Safe Configuration Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/types.md Shows how to define a type-safe configuration object for the eBay API using imported types like AppConfig, SiteId, and MarketplaceId. ```typescript // Type-safe configuration const config: AppConfig = { appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', sandbox: false, siteId: SiteId.EBAY_DE, marketplaceId: MarketplaceId.EBAY_DE, contentLanguage: ContentLanguage.de_DE }; ``` -------------------------------- ### Example: Using getApplicationAccessToken Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/OAuth2.md Illustrates the use of `getApplicationAccessToken`, noting that it's automatically invoked when a user token is unavailable. This ensures an application token is ready for API calls. ```typescript // Automatically called when user token not available const token = await eBay.OAuth2.getApplicationAccessToken(); ``` -------------------------------- ### eBay API Environment Variables Source: https://github.com/hendt/ebay-api/blob/master/examples/README.md Set these environment variables before running the examples to authenticate with the eBay API. Ensure you replace the placeholder values with your actual credentials. ```bash EBAY_APP_ID= EBAY_CERT_ID= EBAY_DEV_ID= EBAY_RU_NAME= DEBUGX=ebay:*; ``` -------------------------------- ### Basic Error Handling Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/errors.md A simple try-catch block demonstrating how to access error metadata like status, URL, and domain when an EBayApiError occurs. ```typescript try { await eBay.buy.browse.search({q: 'iphone'}); } catch (error) { if (error instanceof EBayApiError) { console.log('Status:', error.meta?.res?.status); console.log('URL:', error.meta?.req?.url); console.log('Error domain:', error.meta?.domain); } } ``` -------------------------------- ### Type-Safe Token Handling Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/types.md Illustrates how to define a type-safe authentication token object using the AuthToken type. ```typescript // Type-safe token handling const token: AuthToken = { access_token: '...', refresh_token: '...', expires_in: 7200 }; ``` -------------------------------- ### eBay.buy.marketing.getAlsoBoughtProducts Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get a list of products that were also bought with a specified item. ```APIDOC ## GET /buy/marketing/v1/item/{itemId}/also_bought_products ### Description Retrieves a list of products that customers frequently purchased together with the specified item. ### Method GET ### Endpoint /buy/marketing/v1/item/{itemId}/also_bought_products ### Parameters #### Path Parameters - **itemId** (string) - Required - The ID of the item for which to find also-bought products. ### Response #### Success Response (200) - **products** (array) - A list of products that were also bought. #### Response Example ```json { "products": [ { "itemId": "222222222222", "title": "Related Product 1" } ] } ``` ``` -------------------------------- ### Traditional Methods (Promises) Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Examples of how to call Traditional API methods (like Trading API) using Promises, including simple calls, methods with parameters, and methods with options. ```APIDOC ## Traditional Methods (Promises) ### Description Examples of how to call Traditional API methods (like Trading API) using Promises, including simple calls, methods with parameters, and methods with options. ### Simple XML Method Example ```typescript const result = await eBay.trading.GetAccount(); ``` ### Method with Parameters Example ```typescript const result = await eBay.trading.GetItem({ ItemID: '123456789' }); ``` ### Method with Options Example ```typescript const result = await eBay.trading.GetItem( {ItemID: '123456789'}, {raw: true} // Return raw XML ); ``` ### Parameters Most Trading API methods accept: - `params` - XML request object - `options` - Request options (raw, parseOptions, headers, etc.) ``` -------------------------------- ### Load Configuration from .env File Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/configuration.md Load eBay API configuration from a .env file using the dotenv package. Ensure dotenv is installed and configured before calling eBayApi.fromEnv(). ```typescript import dotenv from 'dotenv'; import eBayApi from 'ebay-api'; dotenv.config(); const eBay = eBayApi.fromEnv(); ``` -------------------------------- ### Using Signed Requests for Fulfillment Operations Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/configuration.md Example of issuing a refund using a signed request. This demonstrates how to apply signatures to fulfillment-related API calls. ```typescript // Fulfillment refund (requires signature) const result = await eBay.sell.fulfillment.sign.issueRefund({...}); ``` -------------------------------- ### GetAccount Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/TradingAPI.md Retrieves account information for the authenticated user. This is a basic example demonstrating a direct API call. ```APIDOC ## GetAccount ### Description Retrieves account information for the authenticated user. ### Method POST ### Endpoint /trading/GetAccount ### Parameters #### Request Body - **null** (object) - Optional - Placeholder for request parameters, often null for simple calls. - **options** (object) - Optional - Configuration options for the call, such as digital signing. - **sign** (boolean) - Optional - If true, signs the request for sensitive operations (e.g., for EU/UK sellers). ### Request Example ```json { "null": null, "options": { "sign": true } } ``` ### Response #### Success Response (200) - **User** (object) - Contains user-specific account details. - **FeedbackScore** (number) - The user's feedback score. #### Response Example ```json { "User": { "FeedbackScore": 1000 } } ``` ``` -------------------------------- ### Import eBay API using ESM in Browser Source: https://github.com/hendt/ebay-api/blob/master/README.md Import the eBay API library using ES Modules (ESM) for browser usage. This example shows how to import from a CDN. ```html ``` -------------------------------- ### Traditional API Type Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/types.md Illustrates the proxy object structure for traditional eBay APIs like Trading, Shopping, and Finding, where each property maps to an API method returning promises. ```typescript const Trading = { GetAccount: async (params) => AccountResponse, GetItem: async (params) => ItemResponse, AddFixedPriceItem: async (params) => AddItemResponse, // ... all Trading API methods } ``` -------------------------------- ### Single-User (Non-Web) AuthNAuth Example Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/AuthNAuth.md Example for obtaining an AuthNAuth token for single-user or non-web applications. It demonstrates getting a session ID, redirect URL, and then obtaining the token. ```typescript import eBayApi from 'ebay-api'; const eBay = new eBayApi({ appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', devId: 'YOUR_DEV_ID', siteId: eBayApi.SiteId.EBAY_US, sandbox: false }); // Get session and login URL const {sessionId, url} = await eBay.authNAuth.getSessionIdAndAuthUrl( 'https://your-app.example.com/callback' ); console.log('Open this URL in browser:', url); console.log('After login, get sessionId from redirect and call:'); // After user logs in (simulated) const userSessionId = 'SESSION_ID_FROM_REDIRECT'; const token = await eBay.authNAuth.obtainToken(userSessionId); console.log('Auth token valid until:', token.HardExpirationTime); // Now use Trading API with token const account = await eBay.trading.GetAccount(); console.log('Account:', account); ``` -------------------------------- ### Get Seller Orders Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/TradingAPI.md Fetch seller orders, allowing filtering by order role and status. This example retrieves completed orders. ```typescript const orders = await eBay.trading.GetOrders({ OrderRole: 'Seller', OrderStatus: 'Completed' }); orders.OrderArray?.Order?.forEach(order => { console.log(`Order: ${order.OrderID}`); console.log(` Total: ${order.Total?.value}`); console.log(` Status: ${order.OrderStatus}`); }); ``` -------------------------------- ### Item Details Response Structure Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/BuyBrowse.md This is an example of the detailed structure for an individual item, retrieved using the getItem method. It includes comprehensive information such as description, shipping options, and return policy. ```typescript { itemId: string title: string subtitle: string description: string price: {value: string, currency: string} condition: string conditionId: string itemCreationDate: string shippingOptions: Array<{ shippingServiceCode: string shippingCost: {value: string, currency: string} minDeliveryDate: string maxDeliveryDate: string }> seller: { username: string sellerAccountType: string feedbackScore: number feedbackPercentage: string } returnPolicy: { returnsAccepted: boolean returnsWithin: string refundMethod: string } // ... many more fields } ``` -------------------------------- ### Using Signed Requests for Trading API Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/configuration.md Example of using the `sign: true` option for requests made to the traditional Trading API. This ensures the request is properly signed. ```typescript // Traditional Trading API const account = await eBay.trading.GetAccount(null, {sign: true}); ``` -------------------------------- ### Express.js AuthNAuth Flow Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/AuthNAuth.md Complete example of the AuthNAuth flow in an Express.js application, including starting the flow, handling the callback, and using the obtained token for API calls. ```typescript import express from 'express'; import session from 'express-session'; import eBayApi from 'ebay-api'; const app = express(); app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true })); const eBay = new eBayApi({ appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', devId: 'YOUR_DEV_ID', ruName: 'https://your-app.example.com/callback', siteId: eBayApi.SiteId.EBAY_US, sandbox: false }); // 1. Start Auth'N'Auth flow app.get('/auth/ebay', async (req, res) => { try { const {sessionId, url} = await eBay.authNAuth.getSessionIdAndAuthUrl(); // Store sessionId in session for callback req.session.ebaySessionId = sessionId; // Redirect user to eBay login res.redirect(url); } catch (error) { console.error('Error starting Auth\'N\'Auth:', error); res.status(500).send('Authentication error'); } }); // 2. Handle callback after user logs in app.get('/callback', async (req, res) => { try { const sessionId = req.session.ebaySessionId; if (!sessionId) { return res.status(400).send('Session ID not found'); } // Get token using sessionId const token = await eBay.authNAuth.obtainToken(sessionId); // Store token in session req.session.ebayToken = token.eBayAuthToken; res.redirect('/dashboard'); } catch (error) { console.error('Error obtaining token:', error); res.status(400).send('Authentication failed'); } }); // 3. Use token in Trading API calls app.get('/api/account', async (req, res) => { if (!req.session.ebayToken) { return res.status(403).json({error: 'Not authenticated'}); } // Create new instance with token const eBayWithToken = new eBayApi({ appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', devId: 'YOUR_DEV_ID', authToken: req.session.ebayToken, siteId: eBayApi.SiteId.EBAY_US, sandbox: false }); try { const account = await eBayWithToken.trading.GetAccount(); res.json(account); } catch (error) { console.error('API error:', error); res.status(500).json({error: 'API request failed'}); } }); // 4. Logout app.get('/logout', (req, res) => { req.session.destroy(); res.redirect('/'); }); ``` -------------------------------- ### Example: Using obtainApplicationAccessToken and Event Listener Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/OAuth2.md Shows how to obtain a new application token using `obtainApplicationAccessToken` and set up an event listener for the `refreshClientToken` event. This allows for saving the refreshed token to a database or other persistent storage. ```typescript const token = await eBay.OAuth2.obtainApplicationAccessToken(); eBay.OAuth2.on('refreshClientToken', (newToken) => { // Save token to database console.log('Token refreshed:', newToken); }); ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/INDEX.md Loads eBay API credentials and settings from environment variables. Ensure EBAY_APP_ID, EBAY_CERT_ID, EBAY_DEV_ID, EBAY_SANDBOX, and EBAY_MARKETPLACE_ID are set. ```bash EBAY_APP_ID=your_app_id EBAY_CERT_ID=your_cert_id EBAY_DEV_ID=your_dev_id EBAY_SANDBOX=false EBAY_MARKETPLACE_ID=EBAY_US ``` ```typescript const eBay = eBayApi.fromEnv(); ``` -------------------------------- ### eBayApi.fromEnv Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/eBayApi.md Loads eBay API configuration from environment variables and returns an instance of eBayApi. Throws ApiEnvError if required variables are missing. ```APIDOC ## eBayApi.fromEnv ### Description Loads eBay API configuration from environment variables and returns an instance of eBayApi. Throws ApiEnvError if required variables are missing. ### Method Signature ```typescript static fromEnv(req?: IEBayApiRequest): eBayApi ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Environment Variables: - `EBAY_APP_ID` (required) - App ID/Client ID - `EBAY_CERT_ID` (required) - Cert ID/Client Secret - `EBAY_DEV_ID` (optional) - Dev ID for Traditional APIs - `EBAY_AUTH_TOKEN` (optional) - Auth'N'Auth token - `EBAY_SITE_ID` (optional) - Site ID (parsed as integer) - `EBAY_MARKETPLACE_ID` (optional) - Marketplace ID - `EBAY_RU_NAME` (optional) - Redirect URI name - `EBAY_SANDBOX` (optional) - Set to 'true' to use sandbox - `EBAY_JWE` (optional) - JWE for digital signature - `EBAY_PRIVATE_KEY` (optional) - Private key for digital signature ### Example Usage ```typescript import eBayApi from 'ebay-api'; const eBay = eBayApi.fromEnv(); const item = await eBay.buy.browse.getItem('v1|254188828753|0'); ``` ``` -------------------------------- ### Initialize eBay API with Configuration Object Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/eBayApi.md Initializes the eBay API client with explicit configuration, including API credentials and marketplace. Useful for direct configuration instead of environment variables. ```typescript import eBayApi from 'ebay-api'; // Initialize with configuration const eBay = new eBayApi({ appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', sandbox: false, marketplaceId: eBayApi.MarketplaceId.EBAY_US }); // RESTful API - Browse const items = await eBay.buy.browse.search({ q: 'iphone' }); // Traditional API - Trading const account = await eBay.trading.GetAccount(null, { headers: { 'X-EBAY-API-COMPATIBILITY-LEVEL': 967 } }); ``` -------------------------------- ### Load eBay API Configuration from Environment Source: https://github.com/hendt/ebay-api/blob/master/README.md Use `eBayApi.fromEnv()` to load configuration from environment variables. Ensure all necessary variables like appId, certId, and authToken are set. ```javascript import eBayApi from 'ebay-api'; // 1. Create new eBayApi instance and set the scope. const eBay = eBayApi.fromEnv(); eBay.OAuth2.setScope([ 'https://api.ebay.com/oauth/api_scope', 'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly', 'https://api.ebay.com/oauth/api_scope/sell.fulfillment' ]); // 2. Generate and open Url and Grant Access const url = eBay.OAuth2.generateAuthUrl(); console.log('Open URL', url); ``` -------------------------------- ### Initialize eBay API from Environment Variables Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/eBayApi.md Loads API configuration from environment variables. Ensure EBAY_APP_ID and EBAY_CERT_ID are set. Throws ApiEnvError if required variables are missing. ```typescript import eBayApi from 'ebay-api'; const eBay = eBayApi.fromEnv(); const item = await eBay.buy.browse.getItem('v1|254188828753|0'); ``` -------------------------------- ### eBayApi Constructor Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/eBayApi.md Initializes the eBay API client with configuration and an optional HTTP request implementation. ```APIDOC ## eBayApi Constructor ### Description Initializes the eBay API client with configuration and an optional HTTP request implementation. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```typescript new eBayApi(config: AppConfig, req?: IEBayApiRequest) ``` ### Parameters - **config** (AppConfig) - Required - Configuration object with API credentials and settings - **req** (IEBayApiRequest) - Optional - HTTP request implementation (for testing/customization) ``` -------------------------------- ### Execute Project Build and Maintenance Commands Source: https://github.com/hendt/ebay-api/blob/master/CLAUDE.md Standard npm scripts for building, testing, linting, and releasing the project. ```bash npm run build # Full build: clean → tsc (ESM) → tsc (CJS) → rollup bundles npm run test # Run all tests with mocha npm run lint # ESLint check npm run lint:fix # ESLint auto-fix npm run report # Run tests with c8 coverage npm run release # Bump version + update CHANGELOG (standard-version) npm run gen-openapi # Regenerate TypeScript types from OpenAPI specs ``` -------------------------------- ### eBay.sell.recommendation Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Provides methods to get recommendations for sellers. ```APIDOC ## eBay.sell.recommendation ### Description Methods for retrieving recommendations. ### Methods - **getRecommendations(params)**: Get recommendations based on provided parameters. ``` -------------------------------- ### eBay.commerce.notification.getSubscriptionsByTopic Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get subscriptions for a specific notification topic. ```APIDOC ## GET /commerce/notification/v1/topic/{topicId}/subscriptions ### Description Retrieves a list of subscriptions associated with a specific notification topic. ### Method GET ### Endpoint /commerce/notification/v1/topic/{topicId}/subscriptions ### Parameters #### Path Parameters - **topicId** (string) - Required - The unique identifier of the topic. #### Query Parameters - **params** (object) - Optional - Parameters for filtering the subscriptions. ### Response #### Success Response (200) - **subscriptions** (array) - A list of subscriptions for the specified topic. #### Response Example ```json { "subscriptions": [ { "subscriptionId": "sub-jkl345", "topicName": "ITEM_LISTED" } ] } ``` ``` -------------------------------- ### eBay.commerce.identity.getUser Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get information about the currently authenticated user. ```APIDOC ## GET /commerce/identity/v1/user/me ### Description Retrieves information about the currently authenticated user. ### Method GET ### Endpoint /commerce/identity/v1/user/me ### Response #### Success Response (200) - **username** (string) - The username of the authenticated user. - **email** (string) - The email address of the user. #### Response Example ```json { "username": "testuser", "email": "testuser@example.com" } ``` ``` -------------------------------- ### Buy - getItem Source: https://github.com/hendt/ebay-api/blob/master/README.md Demonstrates how to retrieve item details using the `getItem` method from the Buy API's browse module. ```APIDOC ### Buy - getItem ```js iBay.buy.browse.getItem('v1|382282567190|651094235351').then(a => { console.log(a); }).catch(e => { console.log(e); }); ``` ``` -------------------------------- ### eBay.buy.marketplaceInsights.getItemAspects Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get item aspects for a specific item. ```APIDOC ## GET /buy/marketplace_insights/v1/item/{itemId}/aspects ### Description Retrieves the aspects (attributes) associated with a specific item. ### Method GET ### Endpoint /buy/marketplace_insights/v1/item/{itemId}/aspects ### Parameters #### Path Parameters - **itemId** (string) - Required - The ID of the item for which to retrieve aspects. ### Response #### Success Response (200) - **aspects** (array) - A list of aspects for the item. #### Response Example ```json { "aspects": [ { "name": "Color", "value": "Blue" }, { "name": "Size", "value": "Large" } ] } ``` ``` -------------------------------- ### eBay.buy.marketing.getMerchandisedProducts Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get merchandised products based on specified parameters. ```APIDOC ## GET /buy/marketing/v1/merchandised_product ### Description Retrieves a list of merchandised products based on various parameters, such as item ID or category. ### Method GET ### Endpoint /buy/marketing/v1/merchandised_product ### Parameters #### Query Parameters - **params** (object) - Required - Parameters for merchandising, such as item ID, category ID, or marketplace ID. ### Response #### Success Response (200) - **products** (array) - A list of merchandised products. #### Response Example ```json { "products": [ { "itemId": "444444444444", "title": "Merchandised Item" } ] } ``` ``` -------------------------------- ### eBay.commerce.taxonomy.getDefaultCategoryTreeId Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get the default category tree ID for a specified marketplace. ```APIDOC ## GET /commerce/taxonomy/v1/default_category_tree/{marketplaceId} ### Description Retrieves the default category tree ID for a given eBay marketplace. ### Method GET ### Endpoint /commerce/taxonomy/v1/default_category_tree/{marketplaceId} ### Parameters #### Path Parameters - **marketplaceId** (string) - Required - The ID of the marketplace (e.g., 'EBAY_US'). ### Response #### Success Response (200) - **categoryTreeId** (string) - The default category tree ID for the marketplace. #### Response Example ```json { "categoryTreeId": "catTree-def456" } ``` ``` -------------------------------- ### eBay.commerce.taxonomy.getCategory Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get details for a specific category within a category tree. ```APIDOC ## GET /commerce/taxonomy/v1/category_tree/{categoryTreeId}/category/{categoryId} ### Description Retrieves detailed information about a specific category within a given category tree. ### Method GET ### Endpoint /commerce/taxonomy/v1/category_tree/{categoryTreeId}/category/{categoryId} ### Parameters #### Path Parameters - **categoryTreeId** (string) - Required - The ID of the category tree. - **categoryId** (string) - Required - The ID of the category to retrieve. ### Response #### Success Response (200) - **categoryId** (string) - The category's unique identifier. - **name** (string) - The name of the category. - **parentCategory** (object) - Information about the parent category. #### Response Example ```json { "categoryId": "cat2", "name": "Computers", "parentCategory": { "categoryId": "cat1", "name": "Electronics" } } ``` ``` -------------------------------- ### eBay.buy.marketing.getAlsoViewedProducts Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get a list of products that were also viewed with a specified item. ```APIDOC ## GET /buy/marketing/v1/item/{itemId}/also_viewed_products ### Description Retrieves a list of products that customers frequently viewed alongside the specified item. ### Method GET ### Endpoint /buy/marketing/v1/item/{itemId}/also_viewed_products ### Parameters #### Path Parameters - **itemId** (string) - Required - The ID of the item for which to find also-viewed products. ### Response #### Success Response (200) - **products** (array) - A list of products that were also viewed. #### Response Example ```json { "products": [ { "itemId": "333333333333", "title": "Related Product 2" } ] } ``` ``` -------------------------------- ### Initialize eBay API Client Source: https://github.com/hendt/ebay-api/blob/master/README.md Configure and initialize the eBay API client with necessary credentials and settings for both RESTful and Traditional APIs. Ensure correct IDs and tokens are provided based on the API type and environment. ```typescript import eBayApi from 'ebay-api'; const eBay = new eBayApi({ appId: '-- also called Client ID --', certId: '-- also called Client Secret --', sandbox: false, siteId: eBayApi.SiteId.EBAY_US, // required for traditional APIs, see https://developer.ebay.com/DevZone/merchandising/docs/Concepts/SiteIDToGlobalID.html marketplaceId: eBayApi.MarketplaceId.EBAY_US, // default. required for RESTful APIs acceptLanguage: eBayApi.Locale.en_US, // default contentLanguage: eBayApi.Locale.en_US, // default. // optional parameters, should be omitted if not used devId: '-- devId --', // required for traditional Trading API ruName: '-- eBay Redirect URL name --', // 'RuName' (eBay Redirect URL name) required for authorization code grant authToken: '-- Auth\'n\'Auth for traditional API (used by trading) --', // can be set to use traditional API without code grant }); ``` -------------------------------- ### eBay.buy.deal.getDeal Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get details for a specific deal using its deal ID. ```APIDOC ## GET /buy/deal/v1/deal/{dealId} ### Description Retrieves detailed information about a specific deal using its unique deal ID. ### Method GET ### Endpoint /buy/deal/v1/deal/{dealId} ### Parameters #### Path Parameters - **dealId** (string) - Required - The unique identifier of the deal. ### Response #### Success Response (200) - **dealId** (string) - The deal's unique identifier. - **title** (string) - The title of the deal. - **items** (array) - List of items included in the deal. #### Response Example ```json { "dealId": "deal-xyz789", "title": "Specific Deal Details", "items": [ { "itemId": "123456789012", "title": "Deal Item 1" } ] } ``` ``` -------------------------------- ### eBay.buy.browse.getItemsByItemGroup Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get item variants within a specific item group. ```APIDOC ## GET /buy/browse/v1/item_group/{itemGroupId}/items ### Description Retrieves item variants that belong to a specified item group. ### Method GET ### Endpoint /buy/browse/v1/item_group/{itemGroupId}/items ### Parameters #### Path Parameters - **itemGroupId** (string) - Required - The unique identifier for the item group. ### Response #### Success Response (200) - **items** (array) - A list of item variants within the specified group. #### Response Example ```json { "items": [ { "itemId": "111111111111", "title": "Item Group Variant 1" }, { "itemId": "222222222222", "title": "Item Group Variant 2" } ] } ``` ``` -------------------------------- ### Global Custom Headers Initialization Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/Restful.md Demonstrates how to set global custom headers during the initialization of the eBay API client using `axiosConfig`. ```typescript const eBay = new eBayApi({ // ... config axiosConfig: { headers: { 'X-Custom-Header': 'value' } } }); ``` -------------------------------- ### eBay.buy.browse.getItems Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/API_METHODS_REFERENCE.md Get details for multiple items by providing a list of item IDs. ```APIDOC ## GET /buy/browse/v1/item/get_items ### Description Retrieves details for multiple eBay items based on a list of item IDs. ### Method GET ### Endpoint /buy/browse/v1/item/get_items ### Parameters #### Query Parameters - **params** (object) - Required - Parameters for the request, including a list of item IDs. - **itemIds** (array of strings) - Required - A comma-separated list of item IDs. ### Response #### Success Response (200) - **items** (array) - A list of item details for the requested item IDs. #### Response Example ```json { "items": [ { "itemId": "123456789012", "title": "Item One Details" }, { "itemId": "234567890123", "title": "Item Two Details" } ] } ``` ``` -------------------------------- ### Search for Items and Retrieve Details Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/BuyBrowse.md This snippet demonstrates how to search for items using keywords and then retrieve detailed information for each item found. It requires initialization of the eBayApi client with your application credentials. ```typescript import eBayApi from 'ebay-api'; const eBay = new eBayApi({ appId: 'YOUR_APP_ID', certId: 'YOUR_CERT_ID', sandbox: false }); // Search for items const searchResults = await eBay.buy.browse.search({ q: 'iphone 14 pro', limit: 5, sort: 'price' }); console.log('Search Results:'); for (const itemSummary of searchResults.itemSummaries || []) { console.log(` Item: ${itemSummary.title}`); console.log(` Price: ${itemSummary.price?.value} ${itemSummary.price?.currency}`); console.log(` Condition: ${itemSummary.condition}`); console.log(` Seller: ${itemSummary.seller?.username}`); // Get detailed item information const itemDetails = await eBay.buy.browse.getItem(itemSummary.itemId); console.log(` Description: ${itemDetails.description?.substring(0, 100)}...`); console.log(` Shipping: ${itemDetails.shippingOptions?.[0]?.shippingServiceCode}`); // Check return policy if (itemDetails.returnPolicy) { console.log(` Returns: ${itemDetails.returnPolicy.returnsAccepted}`); } } ``` -------------------------------- ### Get Current OAuth Scopes Source: https://github.com/hendt/ebay-api/blob/master/_autodocs/api-reference/OAuth2.md Retrieves the currently configured OAuth scopes as an array of strings. ```typescript getScope(): string[] ```