### Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/client.md Examples of initializing the EasyPostClient. ```javascript const EasyPostClient = require('@easypost/api'); // Basic initialization const client = new EasyPostClient(process.env.EASYPOST_API_KEY); // With configuration options const client = new EasyPostClient(process.env.EASYPOST_API_KEY, { timeout: 120000, baseUrl: 'https://api.easypost.com/v2/', requestMiddleware: (request) => { console.log('Making request:', request); return request; } }); // In proxy mode (frontend to backend) const client = new EasyPostClient(null, { useProxy: true, baseUrl: 'https://my-backend.com/api/easypost/' }); ``` -------------------------------- ### Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/client.md Examples of using the `makeApiCall()` method. ```javascript const client = new EasyPostClient(apiKey); // GET request with query parameters const shipments = await client.makeApiCall('get', '/shipments', { page_size: 10 }); // POST request with body const newAddress = await client.makeApiCall('post', '/addresses', { address: { street1: '417 MONTGOMERY ST', city: 'SAN FRANCISCO', state: 'CA', zip: '94104', country: 'US' } }); // DELETE request await client.makeApiCall('del', '/webhooks/hook_123'); ``` -------------------------------- ### Basic Configuration Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Example of initializing the EasyPostClient with a timeout and custom base URL. ```javascript const EasyPostClient = require('@easypost/api'); const client = new EasyPostClient(process.env.EASYPOST_API_KEY, { timeout: 120000, // 2 minutes baseUrl: 'https://api.easypost.com/v2/' }); ``` -------------------------------- ### Wrapped Responses for /all Endpoints Source: https://github.com/easypost/easypost-node/blob/master/UPGRADE_GUIDE.md Example of how responses from /all endpoints are now wrapped with their respective object key, including pagination information. ```json { "shipments": [ { "id": "123" }, { "id": "456" } ], "has_more": true } ``` -------------------------------- ### Proxy Mode Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Example of initializing the EasyPostClient in proxy mode for frontend applications. ```javascript const client = new EasyPostClient(null, { useProxy: true, baseUrl: 'https://my-backend.com/api/easypost/', timeout: 30000 }); ``` -------------------------------- ### Default Timeouts for HTTP Requests Source: https://github.com/easypost/easypost-node/blob/master/UPGRADE_GUIDE.md Example of how to set custom HTTP request timeouts in milliseconds. ```javascript // Timeouts are in milliseconds const api = new Api('API_KEY', { timeout: 60000, }); ``` -------------------------------- ### Example of getting the next page of pickups Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/pickup.md Example of getting the next page of pickups. ```javascript const result = await client.Pickup.all(); if (result.has_more) { const nextPage = await client.Pickup.getNextPage(result); } ``` -------------------------------- ### Superagent Middleware Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Example of using superagentMiddleware to integrate with superagent libraries. ```javascript const superagentLib = require('some-superagent-lib'); const client = new EasyPostClient(apiKey, { superagentMiddleware: (agent) => { return superagentLib(agent); } }); ``` -------------------------------- ### Create and Buy Shipment Example Source: https://github.com/easypost/easypost-node/blob/master/README.md A basic example demonstrating how to create a shipment and then buy it using the EasyPost Node client. ```javascript const EasyPostClient = require('@easypost/api'); const client = new EasyPostClient(process.env.EASYPOST_API_KEY); const shipment = await client.Shipment.create({ from_address: { street1: '417 MONTGOMERY ST', street2: 'FLOOR 5', city: 'SAN FRANCISCO', state: 'CA', zip: '94104', country: 'US', company: 'EasyPost', phone: '415-123-4567', }, to_address: { name: 'Dr. Steve Brule', street1: '179 N Harbor Dr', city: 'Redondo Beach', state: 'CA', zip: '90277', country: 'US', phone: '4155559999', }, parcel: { length: 8, width: 5, height: 5, weight: 5, }, }); const boughtShipment = await client.Shipment.buy(shipment.id, shipment.lowestRate()); console.log(boughtShipment); ``` -------------------------------- ### Install the EasyPost API package Source: https://github.com/easypost/easypost-node/blob/master/README.md Installs the EasyPost API package using npm. ```bash npm install --save @easypost/api ``` -------------------------------- ### Example of creating a pickup Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/pickup.md Example of creating a pickup. ```javascript const pickup = await client.Pickup.create({ address: { street1: '417 MONTGOMERY ST', city: 'SAN FRANCISCO', state: 'CA', zip: '94104', country: 'US' }, pickup_date: '2024-01-15', instructions: 'Ring the doorbell' }); console.log(pickup.id); // "pickup_..." console.log(pickup.status); // "scheduled" console.log(pickup.pickup_rates); // Array of available rates ``` -------------------------------- ### Example of retrieving all pickups Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/pickup.md Example of retrieving all pickups. ```javascript const result = await client.Pickup.all({ page_size: 10 }); console.log(result.pickups.length); ``` -------------------------------- ### Install babel-polyfill for older Node versions Source: https://github.com/easypost/easypost-node/blob/master/README.md Installs the babel-polyfill for Node versions less than 6.9. ```bash npm install --save babel-polyfill ``` -------------------------------- ### Request Middleware Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Example of using requestMiddleware to modify requests before they are sent. ```javascript const client = new EasyPostClient(apiKey, { requestMiddleware: (request) => { // Add custom header to all requests request.set('X-Custom-Header', 'value'); // Log request details console.log(`${request.method.toUpperCase()} ${request.url}`); return request; } }); ``` -------------------------------- ### Example of retrieving a pickup Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/pickup.md Example of retrieving a pickup. ```javascript const pickup = await client.Pickup.retrieve('pickup_....'); console.log(pickup.status); console.log(pickup.confirmation_number); ``` -------------------------------- ### Logging All Requests Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md This example demonstrates how to add request and response hooks to log information about each API interaction. ```javascript const client = new EasyPostClient(apiKey); client.addRequestHook((request) => { console.log(`[${request.requestUUID}] ${request.method.toUpperCase()} ${request.path}`); }); client.addResponseHook((response) => { console.log(`[${response.requestUUID}] ${response.httpStatus}`); }); ``` -------------------------------- ### Reseller/Partner Usage Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/user.md This example illustrates how to manage child user accounts for reseller and partner accounts, including creating, retrieving the API key, creating a client for the child account, updating, and deleting. ```javascript // Create a child account const childUser = await client.User.create({ name: 'Customer Account', email: 'customer@example.com' }); // Get the API key for the child account const childApiKey = childUser.api_keys[0].key; // Create a client for the child account const childClient = new EasyPostClient(childApiKey); // Later, manage the child account await client.User.update(childUser.id, { default_carrier_accounts: ['ca_...'] }); // Delete when no longer needed await client.User.delete(childUser.id); ``` -------------------------------- ### Get Rates Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/order.md Get updated rates for all shipments in an order. ```javascript const updated = await client.Order.getRates('order_....'); console.log(updated.shipments[0].rates); // Updated rates ``` -------------------------------- ### Using superagentMiddleware Source: https://github.com/easypost/easypost-node/blob/master/README.md Example of how to use the `superagentMiddleware` option to wrap the superagent instance. ```javascript import superagentLib from 'some-superagent-lib'; const client = new EasyPostClient('my-key', { superagentMiddleware: (s) => superagentLib(s), }); ``` -------------------------------- ### MissingParameterError Example Handling Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of how to catch and handle MissingParameterError. ```javascript try { const client = new EasyPostClient(null); } catch (error) { if (error instanceof require('@easypost/api').MissingParameterError) { console.error('API key is required:', error.message); } } ``` -------------------------------- ### Using HTTP Methods with makeApiCall Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Example of using the HTTP methods constant with the makeApiCall method. ```javascript await client.makeApiCall(EasyPostClient.METHODS.GET, '/shipments'); ``` -------------------------------- ### Example of purchasing a pickup using PickupRate object Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/pickup.md Example of purchasing a pickup using PickupRate object. ```javascript // Using PickupRate object const purchased = await client.Pickup.buy( 'pickup_....', pickup.pickup_rates[0] ); ``` -------------------------------- ### EASYPOST_API_KEY Environment Variable Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Example of setting the EASYPOST_API_KEY environment variable for authentication. ```bash export EASYPOST_API_KEY=sk_test_1234567890abcdef ``` -------------------------------- ### Example of cancelling a pickup Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/pickup.md Example of cancelling a pickup. ```javascript const cancelled = await client.Pickup.cancel('pickup_....'); console.log(cancelled.status); // "cancelled" ``` -------------------------------- ### updateBrand() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/user.md This example demonstrates how to update the branding information for a user account, specifically changing the color and logo. ```javascript const brand = await client.User.updateBrand('user_...', { color: '#0066cc', logo: 'https://example.com/logo.png' }); console.log(`Brand color: ${brand.color}`); ``` -------------------------------- ### allChildren() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/user.md This example demonstrates how to retrieve a paginated list of child users and log their details. It also shows how to check for and retrieve the next page of results. ```javascript const result = await client.User.allChildren({ page_size: 10 }); console.log(`Total child users on page: ${result.children.length}`); result.children.forEach(child => { console.log(`${child.name} - ${child.email}`); }); if (result.has_more) { const nextPage = await client.User.getNextPage(result); } ``` -------------------------------- ### Example of purchasing a pickup using carrier account and service Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/pickup.md Example of purchasing a pickup using carrier account and service. ```javascript // Using carrier account and service const purchased = await client.Pickup.buy( 'pickup_....', 'ca_....', 'USPS' ); console.log(purchased.confirmation_number); ``` -------------------------------- ### Removal of Instance Methods: Old vs. New Approach Source: https://github.com/easypost/easypost-node/blob/master/UPGRADE_GUIDE.md Demonstrates the change from calling methods on local objects to calling them on services with object IDs. ```javascript // Old approach (buy function called on a local shipment object) const api = new Easypost(process.env.EASYPOST_API_KEY); api.Shipment.retrieve('shp_123...').then((shipment) => { shipment.buy(shipment.lowestRate()).then(console.log); }); ``` ```javascript // New approach (buy function called against the Shipment service, of a client object, with the shipment ID passed in) const client = new Easypost(process.env.EASYPOST_API_KEY); const shipment = await client.Shipment.retrieve('shp_123...'); const boughtShipment = client.Shipment.buy(shipment.id, shipment.lowestRate()); console.log(boughtShipment); ``` -------------------------------- ### getNextPage() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/user.md This example shows how to retrieve all child users by repeatedly calling `getNextPage()` until there are no more pages available, logging the name of each child user. ```typescript let result = await client.User.allChildren(); while (result.has_more) { result = await client.User.getNextPage(result); result.children.forEach(child => { console.log(child.name); }); } ``` -------------------------------- ### InvalidParameterError Example Handling Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of how to catch and handle InvalidParameterError. ```javascript try { // Some operation with invalid parameter } catch (error) { if (error instanceof require('@easypost/api').InvalidParameterError) { console.error('Invalid parameter:', error.message); } } ``` -------------------------------- ### copyClient() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/client.md Create a new EasyPostClient instance with the same configuration as an existing client, optionally overriding specific options. ```javascript const originalClient = new EasyPostClient(apiKey); // Create a new client with a different API key const newClient = EasyPostClient.copyClient(originalClient, { apiKey: differentApiKey }); // Create a client with increased timeout const timeoutClient = EasyPostClient.copyClient(originalClient, { timeout: 180000 }); ``` -------------------------------- ### all() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/address.md Retrieve all addresses associated with the current API key. ```javascript const result = await client.Address.all({ page_size: 10 }); console.log(result.addresses.length); console.log(result.has_more); ``` -------------------------------- ### Using requestMiddleware Source: https://github.com/easypost/easypost-node/blob/master/README.md Example of how to use the `requestMiddleware` option to hook into a superagent request. ```javascript import superagentLib from 'some-superagent-lib'; const client = new EasyPostClient('my-key', { requestMiddleware: (r) => { r.someLibFunction(SOME_CONFIG_VALUE); return r; }, }); ``` -------------------------------- ### Create and Update Functions Source: https://github.com/easypost/easypost-node/blob/master/UPGRADE_GUIDE.md Demonstrates the old approach of creating a local object and calling .save() versus the new approach of calling create() against the Parcel service of a client object. ```javascript const api = new Easypost(process.env.EASYPOST_API_KEY); const parcel = new api.Parcel({ length: 20.2, width: 10.9, height: 5, weight: 65.9, }); parcel.save().then(console.log); // New approach (save called against the Parcel service of a client object) const client = new Easypost(process.env.EASYPOST_API_KEY); const parcel = await client.Parcel.create({ length: 20.2, width: 10.9, height: 5, weight: 65.9, }); console.log(parcel); ``` -------------------------------- ### Example: Predefined Package Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/parcel.md Create a parcel using a predefined package size. ```javascript // Create a parcel using a predefined package size const flatParcel = await client.Parcel.create({ predefined_package: 'SmallFlatBox', weight: 3 // ounces }); console.log(flatParcel.id); // "prcl_..." // Dimensions are automatically set by predefined_package ``` -------------------------------- ### create() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/address.md Create a new address. Optionally verify the address in the same request. ```javascript const client = new EasyPostClient(apiKey); const address = await client.Address.create({ street1: '417 MONTGOMERY ST', street2: 'FLOOR 5', city: 'SAN FRANCISCO', state: 'CA', zip: '94104', country: 'US', company: 'EasyPost', }); console.log(address.id); // "adr_..." ``` -------------------------------- ### Batch Workflow Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/batch.md Demonstrates the typical workflow for creating, adding shipments to, purchasing, and retrieving a batch, including monitoring its state and creating a scan form. ```javascript // 1. Create batch with initial shipments const batch = await client.Batch.create({ shipments: [ { from_address: { ... }, to_address: { ... }, parcel: { ... } }, { from_address: { ... }, to_address: { ... }, parcel: { ... } } ] }); console.log(`Batch created: ${batch.id}`); console.log(`State: ${batch.state}`); // "creating" or "created" // 2. Optionally add more shipments before purchasing const additionalShipments = [ { from_address: { ... }, to_address: { ... }, parcel: { ... } } ]; const updatedBatch = await client.Batch.addShipments(batch.id, additionalShipments); console.log(`Total shipments: ${updatedBatch.num_shipments}`); // 3. Purchase all shipments in the batch const purchasedBatch = await client.Batch.purchase(batch.id); console.log(`State: ${purchasedBatch.state}`); // "purchasing" -> "generating_labels" // 4. Monitor batch state let currentBatch = purchasedBatch; while (currentBatch.state !== 'generated_labels') { await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds currentBatch = await client.Batch.retrieve(batch.id); console.log(`State: ${currentBatch.state}`); } // 5. Create scan form for manifesting const batchWithScanForm = await client.Batch.createScanForm(batch.id); console.log(`Scan form URL: ${batchWithScanForm.scan_form.url}`); // 6. Get combined label URL console.log(`Combined labels: ${currentBatch.label_url}`); // 7. Download labels and scan form for carrier pickup ``` -------------------------------- ### createAndVerify() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/address.md Create an address and verify it in a single API call. ```javascript const verified = await client.Address.createAndVerify({ street1: '417 MONTGOMERY ST', city: 'SAN FRANCISCO', state: 'CA', zip: '94104', country: 'US', verify_carrier: true }); console.log(verified.verified); // boolean ``` -------------------------------- ### Pagination Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/README.md Illustrates how to fetch paginated results from list endpoints and how to retrieve subsequent pages. ```typescript interface PaginatedResult { [collectionKey]: T[]; // "shipments", "addresses", etc. has_more: boolean; // Whether more pages exist _params?: object; // Parameters used for the query } // Get first page let result = await client.Shipment.all({ page_size: 10 }); // Get next pages while (result.has_more) { result = await client.Shipment.getNextPage(result); result.shipments.forEach(shipment => { // Process shipment }); } ``` -------------------------------- ### getLowestSmartRate() Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/utilities.md Get the lowest-priced SmartRate matching delivery time criteria. ```typescript getLowestSmartRate( smartRates: object[], deliveryDays: number, deliveryAccuracy: string ): object ``` ```javascript const smartRates = await client.Shipment.getSmartRates('shp_....'); // Get fastest (50th percentile) cheapest rate const fastRate = client.Utils.getLowestSmartRate( smartRates, 2, 'percentile_50' ); // Get reliable (90th percentile) cheapest rate const reliableRate = client.Utils.getLowestSmartRate( smartRates, 5, 'percentile_90' ); // Get conservative (99th percentile) cheapest rate const conservativeRate = client.Utils.getLowestSmartRate( smartRates, 7, 'percentile_99' ); ``` -------------------------------- ### International Shipping Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/customs.md This example demonstrates how to create customs items, customs info, and an international shipment using the EasyPost Node.js library. ```javascript // Create customs items const items = []; items.push(await client.CustomsItem.create({ description: 'Laptop Computer', hs_tariff_code: '8471.30.00', origin_country: 'US', quantity: 1, value: '1200.00' })); items.push(await client.CustomsItem.create({ description: 'USB Cable', hs_tariff_code: '8544.30.20', origin_country: 'CN', quantity: 2, value: '5.00' })); // Create customs info with items const customsInfo = await client.CustomsInfo.create({ contents_type: 'merchandise', contents_explanation: 'Electronics and accessories', customs_certify: true, customs_signer: 'Jane Smith', non_delivery_option: 'return_to_sender', restriction_type: 'none', eel_pfc: 'NOEEI 30.37(a)', customs_items: items }); // Create international shipment with customs info const shipment = await client.Shipment.create({ from_address: { name: 'Sender Name', street1: '123 Main St', city: 'San Francisco', state: 'CA', zip: '94104', country: 'US' }, to_address: { name: 'Recipient Name', street1: '456 Elm St', city: 'London', state: 'LON', zip: 'SW1A 1AA', country: 'GB' }, parcel: { length: 12, width: 8, height: 6, weight: 2 }, customs_info: customsInfo }); console.log('International shipment created with customs info'); console.log(`Rates available: ${shipment.rates.length}`); ``` -------------------------------- ### retrieve() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/address.md Retrieve an address by ID. ```javascript const address = await client.Address.retrieve('adr_....'); console.log(address.street1); ``` -------------------------------- ### Development Commands Source: https://github.com/easypost/easypost-node/blob/master/README.md Common development commands for the EasyPost Node.js client, including installing dependencies, building, linting, testing, and generating documentation. ```bash # Install dependencies just install # Install style guides (Unix only) just install-styleguide # Update dependencies just update # Build the project just build # Lint the project just lint just lint-fix # Run tests (these will be transpiled on the fly) EASYPOST_TEST_API_KEY=123... EASYPOST_PROD_API_KEY=123... just test EASYPOST_TEST_API_KEY=123... EASYPOST_PROD_API_KEY=123... just coverage # Run security analysis just scan # Generate library documentation just docs # Update submodules just update-examples-submodule ``` -------------------------------- ### getNextPage() Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/address.md Retrieve the next page of addresses. ```javascript const result = await client.Address.all(); if (result.has_more) { const nextPage = await client.Address.getNextPage(result); } ``` -------------------------------- ### EASYPOST_API_BASE_URL Environment Variable Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Example of setting the EASYPOST_API_BASE_URL environment variable to override the default API base URL. ```bash export EASYPOST_API_BASE_URL=https://api.easypost.com/v2/ ``` -------------------------------- ### Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/parcel.md Retrieve a previously created parcel by its ID. ```javascript const parcel = await client.Parcel.retrieve('prcl_abc123xyz'); console.log(`Weight: ${parcel.weight}`); console.log(`Dimensions: ${parcel.length}x${parcel.width}x${parcel.height}`); console.log(`Predefined: ${parcel.predefined_package || 'Custom'}`); ``` -------------------------------- ### API Key Authentication Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/README.md Example of setting up the EasyPost client using the standard API Key authentication mode. ```javascript const client = new EasyPostClient(process.env.EASYPOST_API_KEY); ``` -------------------------------- ### RateLimitError Handling with Exponential Backoff Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of how to handle RateLimitError using exponential backoff. ```javascript const retryWithBackoff = async (fn, maxRetries = 3) => { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error instanceof require('@easypost/api').RateLimitError) { const delay = Math.pow(2, i) * 1000; // Exponential backoff await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } }; // Usage await retryWithBackoff(() => client.Shipment.create({ ... })); ``` -------------------------------- ### Catch Specific Errors Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example demonstrating how to catch and handle specific EasyPost errors using instanceof. ```javascript const EasyPost = require('@easypost/api'); try { const shipment = await client.Shipment.create({ ... }); } catch (error) { if (error instanceof EasyPost.InvalidRequestError) { // Handle validation error } else if (error instanceof EasyPost.PaymentError) { // Handle payment error } else if (error instanceof EasyPost.NotFoundError) { // Handle not found } else { // Handle other errors throw error; } } ``` -------------------------------- ### Example: Metric Dimensions Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/parcel.md Create a parcel with metric (cm and grams). ```javascript // Create a parcel with metric (cm and grams) const metricParcel = await client.Parcel.create({ length: 25, // centimeters width: 20, // centimeters height: 15, // centimeters weight: 1000 // grams }); ``` -------------------------------- ### Example: Custom Dimensions Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/parcel.md Create a parcel with custom dimensions. ```javascript // Create a parcel with custom dimensions const parcel = await client.Parcel.create({ length: 10, // inches width: 8, // inches height: 6, // inches weight: 5 // ounces }); console.log(parcel.id); // "prcl_..." console.log(parcel.length); // 10 console.log(parcel.weight); // 5 ``` -------------------------------- ### Create Order Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/order.md Create a new order containing multiple shipments. ```javascript const order = await client.Order.create({ shipments: [ { from_address: { ... }, to_address: { ... }, parcel: { ... } }, { from_address: { ... }, to_address: { ... }, parcel: { ... } } ] }); console.log(order.id); // "order_..." console.log(order.shipments.length); ``` -------------------------------- ### Verify Address Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/address.md This code snippet demonstrates how to verify an address using the `verifyAddress` method and log the verification status and delivery confirmation level. ```javascript const verified = await client.Address.verifyAddress('adr_....'); console.log(verified.verified); // true or false console.log(verified.delivery_confirmation); // Verification level ``` -------------------------------- ### Create a new carrier account Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/carrier_account.md Example of creating a new carrier account with UPS credentials. ```javascript const account = await client.CarrierAccount.create({ type: 'UpsAccount', description: 'Production UPS Account', credentials: { account_number: '1234567890', access_license_number: 'ABC123DEF456', user_id: 'myusername', password: 'mypassword' } }); console.log(account.id); // "ca_..." console.log(account.carrier); // "UPS" ``` -------------------------------- ### Proxy Mode Authentication Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/README.md Example of setting up the EasyPost client for frontend use with Proxy Mode. ```javascript const client = new EasyPostClient(null, { useProxy: true, baseUrl: 'https://my-backend.com/api/easypost/' }); ``` -------------------------------- ### getLowestRate() Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/utilities.md Get the lowest-priced rate from an array of rates, optionally filtered by carriers and services. ```typescript getLowestRate(rates: Rate[], carriers?: string[], services?: string[]): Rate ``` ```javascript const shipment = await client.Shipment.create({ ... }); // Get lowest rate from all carriers const lowestRate = client.Utils.getLowestRate(shipment.rates); // Get lowest rate from specific carriers const uspsRate = client.Utils.getLowestRate( shipment.rates, ['USPS'] ); // Get lowest rate for specific services const expressRate = client.Utils.getLowestRate( shipment.rates, ['USPS', 'UPS'], ['Priority Mail Express', 'Ground'] ); const shipment = await client.Shipment.buy(shipment.id, lowestRate); ``` -------------------------------- ### Report Type Parameter Moved Source: https://github.com/easypost/easypost-node/blob/master/UPGRADE_GUIDE.md Illustrates the change in how the 'type' parameter is handled when creating a Report. ```javascript // Old approach const report = api.Report('payment_log', { more_params: 'here' }).save(); ``` ```javascript // New approach const report = await client.Report.create({ type: 'payment_log', more_params: 'here' }); ``` -------------------------------- ### Buy Order Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/order.md Purchase all shipments in an order using a specified carrier and service. ```javascript const purchased = await client.Order.buy( 'order_....', 'USPS', 'Priority Mail' ); purchased.shipments.forEach(shipment => { console.log(shipment.tracking_code); }); ``` -------------------------------- ### Construct API instance with options Source: https://github.com/easypost/easypost-node/blob/master/README.md Shows how to instantiate the EasyPost client with various configuration options. ```javascript const client = new EasyPostClient(process.env.EASYPOST_API_KEY, { timeout: 120000, baseUrl: 'https://api.easypost.com/v2/', useProxy: false, superagentMiddleware: (s) => s, requestMiddleware: (r) => r, }); ``` -------------------------------- ### Get Next Page of End Shippers Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/end-shipper.md Example of fetching the next page of end shippers from a previous result. ```typescript static async getNextPage(end_shippers: object, pageSize?: number): Promise<{ end_shippers: EndShipper[], has_more: boolean }> ``` ```javascript const result = await client.EndShipper.all(); if (result.has_more) { const nextPage = await client.EndShipper.getNextPage(result); } ``` -------------------------------- ### Setting Up Webhooks Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/README.md Illustrates how to create a webhook subscription for specific events and how to validate incoming webhook signatures. ```javascript // Create webhook const webhook = await client.Webhook.create({ url: 'https://example.com/webhooks/easypost', event_types: ['shipment.purchased', 'tracker.updated'] }); console.log(`Webhook ID: ${webhook.id}`); console.log(`Secret: ${webhook.webhook_secret}`); // In your webhook handler app.post('/webhooks/easypost', (req, res) => { const isValid = client.Utils.validateWebhookSignature( req.rawBody, req.get('X-EasyPost-Signature'), webhookSecret ); if (!isValid) { return res.status(401).send('Unauthorized'); } const event = req.body; // Process event... res.status(200).send('OK'); }); ``` -------------------------------- ### HTTP Hooks Source: https://github.com/easypost/easypost-node/blob/master/README.md Example of how to add, remove, and clear request and response hooks for logging outgoing requests and responses from the EasyPost API. ```javascript const client = new EasyPostClient('my-key'); const logOutgoingRequest = (request) => console.log('Outgoing:', request); const logResponse = (response) => console.log('Response:', response); // optionally add your hook to listen for outgoing requests client.addRequestHook(logOutgoingRequest); // and optionally the hook for the response client.addResponseHook(logResponse); // ...do other stuff // remove that request hook client.removeRequestHook(logOutgoingRequest); // and the response one client.removeResponseHook(logResponse); // or clear all the hooks at once client.clearRequestHooks(); client.clearResponseHooks(); ``` -------------------------------- ### Carrier Account Management Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/carrier_account.md Demonstrates how to list, create, update, and delete carrier accounts using the EasyPost API. ```javascript const client = new EasyPostClient(apiKey); // 1. List existing carrier accounts const accounts = await client.CarrierAccount.all(); console.log(`Configured carriers: ${accounts.length}`); // 2. Add a new carrier account const newAccount = await client.CarrierAccount.create({ type: 'UpsAccount', description: 'Primary UPS Account', credentials: { account_number: '1234567890', access_license_number: 'YOUR_LICENSE_NUMBER', user_id: 'your_ups_user', password: 'your_ups_password' } }); console.log(`Created: ${newAccount.id}`); // 3. Update account description const updated = await client.CarrierAccount.update(newAccount.id, { description: 'Updated description' }); // 4. Delete old account if (accounts.length > 1) { const oldAccount = accounts[accounts.length - 1]; const deleted = await client.CarrierAccount.delete(oldAccount.id); console.log(`Deleted carrier account`); } ``` -------------------------------- ### Retrieve all carrier accounts Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/carrier_account.md Example of retrieving all carrier accounts associated with the current API key. ```javascript const accounts = await client.CarrierAccount.all(); accounts.forEach(account => { console.log(`${account.carrier}: ${account.description}`); }); ``` -------------------------------- ### Create End Shipper Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/end-shipper.md Example of creating a new end shipper with various parameters. ```typescript static async create(params: object): Promise ``` ```javascript const endShipper = await client.EndShipper.create({ name: 'John Doe', company: 'Acme Corp', street1: '123 Main St', city: 'Denver', state: 'CO', zip: '80202', country: 'US', phone: '303-123-4567', email: 'john@acme.com' }); console.log(endShipper.id); // "es_..." ``` -------------------------------- ### Creating an International Shipment Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/README.md Provides an example of creating an international shipment by first defining customs items and customs information. ```javascript // Create customs items const items = await Promise.all([ client.CustomsItem.create({ description: 'Electronics', hs_tariff_code: '8471.30.00', origin_country: 'US', quantity: 1, value: '500.00' }) ]); // Create customs info const customsInfo = await client.CustomsInfo.create({ contents_type: 'merchandise', customs_certify: true, customs_signer: 'John Doe', non_delivery_option: 'return_to_sender', customs_items: items }); // Create shipment const shipment = await client.Shipment.create({ from_address: { /* US address */ }, to_address: { /* International address */ }, parcel: { /* dimensions */ }, customs_info: customsInfo }); // Proceed with rate selection and purchase ``` -------------------------------- ### recommendShipDate Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/shipment.md Gets recommended ship dates to achieve a desired delivery date. ```typescript static async recommendShipDate(id: string, desiredDeliveryDate: string): Promise> ``` ```javascript const rates = await client.Shipment.recommendShipDate( 'shp_....', '2024-01-20' ); rates.forEach(rate => { console.log(`Ship on ${rate.ship_date} for delivery on ${rate.delivery_date}`); }); ``` -------------------------------- ### Implement Retry Logic Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of a utility function to implement retry logic for API calls with backoff, handling specific retryable errors. ```javascript const retryWithBackoff = async (fn, maxRetries = 3, baseDelay = 1000) => { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await fn(); } catch (error) { const isRetryable = error instanceof EasyPost.RateLimitError || error instanceof EasyPost.TimeoutError || error instanceof EasyPost.InternalServerError || error instanceof EasyPost.ServiceUnavailableError || error instanceof EasyPost.GatewayTimeoutError; if (isRetryable && attempt < maxRetries - 1) { const delay = baseDelay * Math.pow(2, attempt); await new Promise(resolve => setTimeout(resolve, delay)); continue; } throw error; } } }; // Usage const shipment = await retryWithBackoff(() => client.Shipment.create({ ... }) ); ``` -------------------------------- ### IEasyPostOptions Interface Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Defines the available configuration options for the EasyPostClient constructor. ```typescript interface IEasyPostOptions { timeout?: number; baseUrl?: string; useProxy?: boolean; superagentMiddleware?: (agent: any) => any; requestMiddleware?: (request: any) => any; } ``` -------------------------------- ### regenerateRates() - Get updated rates for a shipment Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/shipment.md Get updated rates for a shipment. Useful when rates have changed or shipment details have been modified. ```typescript static async regenerateRates(id: string): Promise ``` ```javascript const updated = await client.Shipment.regenerateRates('shp_....'); console.log(updated.rates); // Array of new Rate objects ``` -------------------------------- ### Finding the Best Rate Based on Delivery Time Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/utilities.md This snippet demonstrates how to find the cheapest smart rate that delivers within a specified timeframe (e.g., 3-5 days) using the `getLowestSmartRate` utility. ```javascript const smartRates = await client.Shipment.getSmartRates('shp_....'); // Find cheapest rate that delivers in 3-5 days (90th percentile) const rate = client.Utils.getLowestSmartRate(smartRates, 5, 'percentile_90'); if (rate) { console.log(`${rate.carrier} ${rate.service}: $${rate.rate}`); console.log(`Estimated delivery: ${rate.delivery_date}`); const purchased = await client.Shipment.buy(shipmentId, rate); } ``` -------------------------------- ### SignatureVerificationError Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of how to verify webhook signatures and handle SignatureVerificationError. ```javascript const verifyWebhook = (body, signature, secret) => { const crypto = require('crypto'); const hash = crypto .createHmac('sha256', secret) .update(body) .digest('hex'); if (hash !== signature) { throw new require('@easypost/api').SignatureVerificationError( 'Webhook signature does not match' ); } }; app.post('/webhooks/easypost', (req, res) => { try { const signature = req.get('X-EasyPost-Signature'); verifyWebhook(req.rawBody, signature, webhookSecret); // Process webhook... } catch (error) { if (error instanceof require('@easypost/api').SignatureVerificationError) { return res.status(401).send('Unauthorized'); } throw error; } }); ``` -------------------------------- ### PaymentError Handling Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of handling a PaymentError, which occurs when a payment fails. ```javascript try { await client.Shipment.buy(shipmentId, rateId); } catch (error) { if (error instanceof require('@easypost/api').PaymentError) { console.error('Payment failed. Please update your billing information.'); } } ``` -------------------------------- ### Constructor Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/client.md Creates a new EasyPost API client instance. ```typescript new EasyPostClient(apiKey: string, options?: IEasyPostOptions) ``` -------------------------------- ### Require babel-polyfill and EasyPost library Source: https://github.com/easypost/easypost-node/blob/master/README.md Demonstrates how to require the babel-polyfill and the EasyPost library in a Node.js project. ```javascript // Require the polyfill if necessary: require('babel-polyfill'); // Require the EasyPost library: const EasyPost = require('@easypost/api'); ``` -------------------------------- ### METHODS Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/client.md HTTP method constants for use with `makeApiCall()`. ```typescript EasyPostClient.METHODS: { GET: 'get', POST: 'post', PUT: 'put', PATCH: 'patch', DELETE: 'del' } ``` -------------------------------- ### Delete a carrier account Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/carrier_account.md Example of deleting a carrier account. ```javascript const deleted = await client.CarrierAccount.delete('ca_....'); ``` -------------------------------- ### EndOfPaginationError Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of how to handle EndOfPaginationError by checking 'has_more' before calling getNextPage or by catching the error. ```javascript let result = await client.Shipment.all(); try { while (result.has_more) { result = await client.Shipment.getNextPage(result); // Process result } } catch (error) { if (error instanceof require('@easypost/api').EndOfPaginationError) { console.log('Reached end of pagination'); } } // Or check before calling: if (result.has_more) { result = await client.Shipment.getNextPage(result); } ``` -------------------------------- ### NotFoundError Handling Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of handling a NotFoundError, which occurs when trying to retrieve a non-existent shipment. ```javascript try { const shipment = await client.Shipment.retrieve('shp_nonexistent'); } catch (error) { if (error instanceof require('@easypost/api').NotFoundError) { console.error('Shipment not found'); } } ``` -------------------------------- ### UnauthorizedError Handling Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of handling an UnauthorizedError, which occurs when an invalid API key is provided. ```javascript try { const client = new EasyPostClient(null); } catch (error) { if (error instanceof require('@easypost/api').UnauthorizedError) { console.error('Invalid API key'); } } ``` -------------------------------- ### HTTP Methods Constant Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Available HTTP methods exposed as a constant on the EasyPostClient. ```typescript EasyPostClient.METHODS = { GET: 'get', POST: 'post', PUT: 'put', PATCH: 'patch', DELETE: 'del' } ``` -------------------------------- ### Retrieve Order Example Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/order.md Retrieve an order by ID. ```javascript const order = await client.Order.retrieve('order_....'); console.log(order.shipments); ``` -------------------------------- ### Create Batch Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/batch.md Create a new batch of shipments. ```typescript static async create(params: object): Promise ``` ```javascript const batch = await client.Batch.create({ shipments: [ { from_address: { ... }, to_address: { ... }, parcel: { ... } }, { from_address: { ... }, to_address: { ... }, parcel: { ... } } ] }); console.log(batch.id); // "batch_..." console.log(batch.state); // "creating" ``` -------------------------------- ### BadRequestError Handling Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/errors.md Example of handling a BadRequestError, which occurs when a request is malformed or missing required parameters. ```javascript try { await client.Shipment.create({ from_address: { ... }, to_address: { ... } // Missing: parcel }); } catch (error) { if (error instanceof require('@easypost/api').BadRequestError) { console.error('Missing required parcel:', error.message); } } ``` -------------------------------- ### Creating and Buying a Shipment Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/README.md Demonstrates how to create a shipment, select the lowest rate, and then buy the shipment using the EasyPost Node.js client. ```javascript const EasyPostClient = require('@easypost/api'); const client = new EasyPostClient(process.env.EASYPOST_API_KEY); // 1. Create shipment const shipment = await client.Shipment.create({ from_address: { street1: '123 Main St', city: 'San Francisco', state: 'CA', zip: '94104', country: 'US' }, to_address: { name: 'Customer Name', street1: '456 Oak Ave', city: 'New York', state: 'NY', zip: '10001', country: 'US' }, parcel: { length: 10, width: 8, height: 6, weight: 2 } }); // 2. Select lowest rate const lowestRate = client.Utils.getLowestRate(shipment.rates); // 3. Buy shipment const purchased = await client.Shipment.buy(shipment.id, lowestRate); console.log(`Tracking: ${purchased.tracking_code}`); console.log(`Label: ${purchased.postage_label.label_url}`); ``` -------------------------------- ### Update a carrier account Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/carrier_account.md Example of updating a carrier account's description. ```javascript const updated = await client.CarrierAccount.update('ca_....', { description: 'Updated description' }); ``` -------------------------------- ### Default Headers Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md Default headers included in every request. ```javascript { 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'EasyPost/v2 NodejsClient/...' } ``` -------------------------------- ### Retrieve a carrier account by ID Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/carrier_account.md Example of retrieving a carrier account by its ID. ```javascript const account = await client.CarrierAccount.retrieve('ca_....'); console.log(account.carrier); console.log(account.test_credentials); ``` -------------------------------- ### createAndBuyLuma() Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/shipment.md Create and immediately purchase a shipment using Luma (all-in-one operation). ```typescript static async createAndBuyLuma(params: object): Promise ``` ```javascript const shipment = await client.Shipment.createAndBuyLuma({ from_address: { ... }, to_address: { ... }, parcel: { ... } }); console.log(shipment.tracking_code); // Already purchased ``` -------------------------------- ### User Agent Format Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/configuration.md The format of the User-Agent header automatically set by the client. ```plaintext EasyPost/v2 NodejsClient/{version} Nodejs/{nodeVersion} OS/{platform} OSVersion/{osVersion} OSArch/{arch} ``` -------------------------------- ### Get Next Page of Batches Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/batch.md Retrieve the next page of batches. ```typescript static async getNextPage(batches: object, pageSize?: number): Promise<{ batches: Batch[], has_more: boolean }> ``` ```javascript const result = await client.Batch.all(); if (result.has_more) { const nextPage = await client.Batch.getNextPage(result); } ``` -------------------------------- ### Finding and Buying with the Lowest Rate Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/utilities.md Common pattern for finding and buying the lowest rate for a shipment. ```javascript const shipment = await client.Shipment.create({ from_address: { ... }, to_address: { ... }, parcel: { ... } }); // Method 1: Use built-in lowestRate() method const lowestRate = shipment.lowestRate(); const boughtShipment = await client.Shipment.buy(shipment.id, lowestRate); // Method 2: Use Utils.getLowestRate() with filters const lowestUspsRate = client.Utils.getLowestRate( shipment.rates, ['USPS'] ); const boughtShipment = await client.Shipment.buy(shipment.id, lowestUspsRate); ``` -------------------------------- ### File Structure Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/README.md The directory structure of the EasyPost Node.js SDK project. ```tree output/ ├── README.md # This file ├── configuration.md # Configuration options ├── types.md # Type definitions ├── errors.md # Error classes and handling └── api-reference/ ├── client.md # EasyPostClient class ├── address.md # Address service ├── shipment.md # Shipment service ├── order.md # Order service ├── batch.md # Batch service ├── parcel.md # Parcel service ├── tracker.md # Tracker service ├── pickup.md # Pickup service ├── webhook.md # Webhook service ├── user.md # User service ├── carrier_account.md # CarrierAccount service ├── customs.md # Customs services ├── end-shipper.md # EndShipper service └── utilities.md # Utility functions ``` -------------------------------- ### Dimension and Weight Units - Centimeters/Grams Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/parcel.md Example of creating a parcel using centimeters for dimensions and grams for weight. ```javascript const parcel = await client.Parcel.create({ length: 30, // centimeters width: 23, height: 15, weight: 70 // grams }); ``` -------------------------------- ### Dimension and Weight Units - Inches/Ounces Source: https://github.com/easypost/easypost-node/blob/master/_autodocs/api-reference/parcel.md Example of creating a parcel using inches for dimensions and ounces for weight. ```javascript const parcel = await client.Parcel.create({ length: 12, // inches width: 9, height: 6, weight: 2.5 // ounces }); ```