EasyPost Node Client Library

repository·master·Indexed 40 days ago

https://github.com/easypost/easypost-node

A programmatic interface for the EasyPost shipping API in Node.js. Use the @easypost/api package (version 9.0.0-rc.1) to create shipments, purchase labels, manage logistics, and handle carrier accounts. Features include built-in TypeScript support since v5.3.0, HTTP middleware for request modification, and specialized services for addresses, API keys, batches, and billing.

Tokens
13.3K
Snippets
70
Records
82
Agent score
100%

What's inside EasyPost

  1. Handle wrapped responses for /all endpoints (v5.0)

    master

    In version 5.0, responses from /all endpoints are no longer unwrapped. They now follow the official documentation where records are wrapped within their respective object key. This change enables proper pagination by allowing you to check for the has_more key.

    Example response structure:

    {
      "shipments": [
        {
          "id": "123"
        },
        {
          "id": "456"
        }
      ],
      "has_more": true
    }
    {
      "shipments": [
        {
          "id": "123"
        },
        {
          "id": "456"
        }
      ],
      "has_more": true
    }
  2. TypeScript support in @easypost/api

    master

    Since version v5.3.0, the library includes built-in TypeScript definitions located in dist/types. No additional configuration is required when importing @easypost/api from the package root.

    Exclusions: Note that the following are not provided via these definitions:

    • Predefined packages (e.g., Carrier Metadata)
    • Carrier service levels
    • Carrier lists
    • Comprehensive parameter/property requirements (refer to official documentation for specific request requirements)
  3. Migrate from 5.x to 9.0

    master

    When upgrading to version 9.0, several high-impact changes affect how data is received and how the HTTP transport layer operates.

    Response Objects

    Response objects are now plain JSON objects. This change affects how you parse and interact with the data returned from the API.

    HTTP Transport

    The HTTP transport layer has migrated to fetch. Ensure your environment supports fetch or provides a polyfill if running in older Node.js versions.

    Type Optionality

    Type optionality has been relaxed, meaning certain fields that were previously optional in TypeScript definitions may now be required to ensure type safety and alignment with the API.

    retrieveStatelessRates Behavior

    The retrieveStatelessRates method now returns the full response object rather than a subset of the data.

    Type Declarations

    Type declarations are now source-generated, which may affect how you extend or reference types in your own TypeScript code.

  4. Migrate from 4.x to 5.0 (Deprecated Versions)

    master

    Note that v4 and v5 are both deprecated.

    4.0 JSON Encoded Bodies

    In version 4.0, all POST and PUT request bodies changed from form-encoded to JSON encoded. This may cause subtle inconsistencies in how certain data types are sent to the API.

    4.0 HTTP Method Change for retrieveRates()

    In version 4.0, the HTTP method for retrieveRates() changed from POST to GET. In this version, retrieveRates only retrieves existing rates for a shipment, while regenerateRates was introduced to handle POST requests for updated rates.

  5. Upgrade from 8.x to 9.0

    master

    Upgrading to version 9.0 involves several high and medium impact changes, primarily due to a shift in how API responses are structured and how HTTP requests are handled.

    Key Changes

    • Response Objects: API responses are now plain JSON-compatible objects instead of model class instances. While helper methods like shipment.lowestRate() are preserved on these objects, instanceof model checks may no longer work as expected.
    • HTTP Transport: The library has migrated from superagent to fetch. This requires Node 18+.
    • Method Renaming: agent is now httpClient, and superagentMiddleware is replaced by httpMiddleware.
    • API Call Aliases: The del alias for makeApiCall has been removed; use delete instead.
    • Stateless Rates: retrieveStatelessRates now returns the full response object. You must access the rates via response.rates.
    ### 9.0 Migration Checklist
    - Ensure runtime is Node 18+.
    - Replace `superagentMiddleware` with `httpMiddleware`.
    - Replace `agent` with `httpClient`.
    - Replace `makeApiCall('del', ...)` with `makeApiCall('delete', ...)`.
    - If you use `retrieveStatelessRates`, read rates from `response.rates`.
    - If you import from internal `types/` paths, migrate to package-root imports.
    
    ### 9.0 HTTP Transport Migration Example
    ```javascript
    // After
    const client = new EasyPostClient('api_key', {
      httpMiddleware: (httpFn) => httpFn,
      httpClient: fetch,
    });

    9.0 retrieveStatelessRates Usage

    // Before
    const rates = await client.BetaRate.retrieveStatelessRates(params);
    
    // After
    const response = await client.BetaRate.retrieveStatelessRates(params);
    const rates = response.rates;
  6. Upgrade from 6.x to 7.0

    master

    Note that v7 is deprecated.

    Key Changes

    • Carbon Offset Removal: EasyPost now provides Carbon Neutral shipments by default for free. The withCarbonOffset parameter has been removed from create, buy, and regenerateRates shipment functions. If you use EndShippers, you must inspect your callsites to ensure the EndShipper parameter is passed correctly now that withCarbonOffset is gone.
    • Batch Function Removal: The createAndBuy() Batch endpoint has been removed. You must now use two separate API calls: first to create a batch, then to purchase it.
  7. Upgrade from 5.x to 6.0

    master

    Note that v6 is deprecated. This version introduced significant architectural changes to how objects are managed and how errors are handled.

    Key Changes

    • Node Requirement: Requires Node 12+.
    • Service-Based Pattern: Instance methods like .save(), .delete(), and .buy() have been removed. You must now call these methods against a service (e.g., client.Parcel.create()) and pass the object ID where necessary.
    • Async Methods: All functions attached to a service are now asynchronous and must be awaited.
    • Error Handling: A new hierarchy of ~24 error types has been introduced, categorized into ApiError (for API-related issues like invalid_request_error or rate_limit_error) and EasyPostError (for library-level issues like invalid_parameter_error).
    • Report Creation: The type parameter for Reports is now nested inside the params object.
    // 6.0 New approach (create/update called against a service)
    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,
    });
    
    // 6.0 New approach (buy function called against the Shipment service)
    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());
    
    // 6.0 New approach (Report creation with nested type)
    const report = await client.Report.create({ type: 'payment_log', more_params: 'here' });
  8. Install @easypost/api via npm

    master

    Install the EasyPost Node client library using npm to integrate shipping capabilities into your backend Node.js service.

    Note: This library is intended for backend Node services and should not be used in frontend JavaScript projects via the browser.

    npm install --save @easypost/api
  9. Paginate through child users

    master

    To manage large lists of child users, use the following pattern:

    1. UserService.allChildren(params): Retrieves the initial list of child users and pagination metadata.
    2. UserService.getNextPage(children, pageSize): Retrieves the next page of results using the metadata from the previous response.

    If no more pages are available, getNextPage will throw an EndOfPaginationError.

    // 1. Get the first page
    const firstPage = await UserService.allChildren({});
    
    // 2. Get the next page if has_more is true
    if (firstPage.has_more) {
      const secondPage = await UserService.getNextPage(firstPage, 50);
    }
  10. Configure EasyPostClient options

    master

    When instantiating EasyPostClient, you can provide an options object to customize the client behavior. Supported options include:

    • timeout: Time in milliseconds before a request fails.
    • baseUrl: The base URL for API requests (useful for proxying).
    • useProxy: If true, disables using the API key (useful when proxying from a frontend through a server).
    • httpMiddleware: A function that wraps the underlying HTTP transport function.
    • httpClient: The function used for HTTP requests. Defaults to built-in fetch (Node 18+).
    • requestMiddleware: A function that takes a compatibility request object and returns it. Supports patterns using auth, query, and send.
    const client = new EasyPostClient(process.env.EASYPOST_API_KEY, {
      timeout: 120000,
      baseUrl: 'https://api.easypost.com/v2/',
      useProxy: false,
      httpMiddleware: (f) => f,
      httpClient: fetch,
      requestMiddleware: (r) => r,
    });