### Setup Nova Poshta Carrier API Project (Bash) Source: https://github.com/shopanaio/carrier-api/blob/main/README.md These bash commands outline the initial setup process for the carrier-api project. It involves cloning the repository, installing project dependencies using Yarn Workspaces, and building all packages within the monorepo. These steps are crucial for setting up the development environment. ```bash # Clone the repository git clone https://github.com/shopanaio/carrier-api.git cd carrier-api # Install dependencies yarn install # Build all packages yarn build ``` -------------------------------- ### Install @shopana/novaposhta-transport-fetch Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-transport-fetch/README.md Installs the @shopana/novaposhta-transport-fetch package using either yarn or npm package managers. This is the first step to integrate the transport layer into your project. ```bash yarn add @shopana/novaposhta-transport-fetch # or npm i @shopana/novaposhta-transport-fetch ``` -------------------------------- ### Full Fetch Transport Configuration Example (TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-transport-fetch/README.md A comprehensive example demonstrating the initialization of the Novaposhta client with a fetch transport that has both a custom fetch implementation and custom base headers configured. This allows for fine-grained control over API communication. ```typescript const transport = createFetchHttpTransport({ fetchImpl: customFetch, baseHeaders: { 'X-Custom-Header': 'value', }, }); const client = createClient({ transport, baseUrl: 'https://api.novaposhta.ua/v2.0/json/', }); ``` -------------------------------- ### Install Nova Poshta API Client and Transport Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/README.md Install the core Nova Poshta API client package along with the fetch-based HTTP transport using npm, yarn, or pnpm. The transport is optional and can be replaced with a custom implementation. ```bash npm install @shopana/novaposhta-api-client @shopana/novaposhta-transport-fetch ``` ```bash yarn add @shopana/novaposhta-api-client @shopana/novaposhta-transport-fetch ``` ```bash pnpm add @shopana/novaposhta-api-client @shopana/novaposhta-transport-fetch ``` -------------------------------- ### Get Reference Dictionaries (TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/README.md Provides examples of retrieving various reference data from the API, such as payer types, payment forms, counterparty types, cargo types, and service types. These methods help to populate dropdowns or validate input. Requires an initialized client. ```typescript // Get payer types (Sender/Recipient/ThirdPerson) const payerTypes = await client.reference.getTypesOfPayers(); // Get payment forms (Cash/NonCash) const paymentForms = await client.reference.getPaymentForms(); // Get counterparty types (PrivatePerson/Organization) const counterpartyTypes = await client.reference.getTypesOfCounterparties(); // Get cargo types const cargoTypes = await client.reference.getCargoTypes(); // Get service types (warehouse-warehouse, door-warehouse, etc.) const serviceTypes = await client.reference.getServiceTypes(); ``` -------------------------------- ### Install Nova Poshta API Client and Fetch Transport Source: https://github.com/shopanaio/carrier-api/blob/main/README.md Installs the Nova Poshta API client and the fetch-based HTTP transport. This combination allows for cross-platform usage in Node.js, browsers, and edge runtimes. ```bash npm i @shopana/novaposhta-api-client @shopana/novaposhta-transport-fetch ``` -------------------------------- ### GET /getCities Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/docs/novaposhta-2.0/1_3_zavantazhiti_dovdnik_mst_kompan_nova_poshta_met.html Retrieves the directory of cities for the Nova Poshta company. ```APIDOC ## GET /getCities ### Description This endpoint allows you to download the directory of cities for the Nova Poshta company. ### Method GET ### Endpoint /getCities ### Parameters #### Query Parameters - **apiKey** (string) - Required - Your unique API key. ### Request Example ```json { "apiKey": "YOUR_API_KEY" } ``` ### Response #### Success Response (200) - **data** (array) - An array of city objects. - **cityRef** (string) - The unique reference for the city. - **cityDescription** (string) - The name of the city. - **area** (string) - The region or area the city belongs to. - **regionDescription** (string) - The name of the region. - **index10** (string) - Index for 10kg parcels. - **index30** (string) - Index for 30kg parcels. - **areaWithAddressType** (string) - Indicates if the area has a specific address type. #### Response Example ```json { "success": true, "data": [ { "Ref": "8d551580-e95f-11e0-8d87-00155d93f118", "Description": "Київ", "DescriptionRu": "Киев", "Area": "96e35767-e930-11e0-8d87-00155d93f118", "AreaDescription": "Київська", "AreaDescriptionRu": "Киевская", "Index10": "10000", "Index30": "10000", "IsBranch": "0", "AddressType": "City" } ], "errors": [], "warnings": [], "info": [], "messageCodes": [], "errorCodes": [], "warningCodes": [], "infoCodes": [] } ``` ``` -------------------------------- ### Get Counterparties in TypeScript Source: https://context7.com/shopanaio/carrier-api/llms.txt This snippet demonstrates how to retrieve and display counterparties, such as senders and recipients. It allows filtering by property and a search string, and then logs the description and reference of each counterparty. ```typescript ```typescript const senders = await client.counterparty.getCounterparties({ CounterpartyProperty: 'Sender', Page: 1 }); console.log('Your senders:'); senders.data.forEach(sender => { console.log(` ${sender.Description} (${sender.Ref})`); }); const recipients = await client.counterparty.getCounterparties({ CounterpartyProperty: 'Recipient', FindByString: 'Петров', Page: 1 }); console.log('\nRecipients matching "Петров":'); recipients.data.forEach(recipient => { console.log(` ${recipient.Description} (${recipient.Ref})`); }); ``` ``` -------------------------------- ### GET /reference_get_pack_list Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md List available packaging types with standard package dimensions and descriptions. Useful for calculating delivery costs. Recommended to cache monthly. ```APIDOC ## GET /reference_get_pack_list ### Description List available packaging types with standard package dimensions and descriptions. Useful for calculating delivery costs. Cache monthly. ### Method GET ### Endpoint /reference_get_pack_list ### Response #### Success Response (200) - **PackageTypes** (array) - Array of available packaging types - **Ref** (string) - Reference identifier - **Description** (string) - Package type description - **Length** (number) - Length in cm - **Width** (number) - Width in cm - **Height** (number) - Height in cm - **MaxWeight** (number) - Maximum weight in kg #### Response Example { "PackageTypes": [ { "Ref": "pack_001", "Description": "Small box", "Length": 20, "Width": 15, "Height": 10, "MaxWeight": 5 } ] } ``` -------------------------------- ### ReferenceService Usage Example Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/referenceService.ts.html Demonstrates practical usage of ReferenceService methods including retrieving cargo types, pallets list, and pack list with optional dimension filters. Shows how to call async methods and handle responses. ```typescript // Get cargo types const cargoTypes = await referenceService.getCargoTypes(); // Get pallets list const pallets = await referenceService.getPalletsList(); // Get pack list with filters const packs = await referenceService.getPackList({ length: 100, width: 50, height: 30 }); ``` -------------------------------- ### GET /reference_get_tires_wheels_list Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md List available tires and wheels types with descriptions for shipping as cargo. Recommended to cache monthly. ```APIDOC ## GET /reference_get_tires_wheels_list ### Description List available tires and wheels types. Returns types and descriptions for shipping tires and wheels as cargo. Cache monthly. ### Method GET ### Endpoint /reference_get_tires_wheels_list ### Response #### Success Response (200) - **TiresWheels** (array) - Array of tire and wheel types - **Ref** (string) - Reference identifier - **Description** (string) - Type description - **Value** (string) - Type value #### Response Example { "TiresWheels": [ { "Ref": "tire_001", "Description": "Summer tires R17", "Value": "SummerR17" } ] } ``` -------------------------------- ### GET /reference_get_cargo_description_list Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md List cargo descriptions with optional search. Returns predefined descriptions for common cargo types. Recommended to cache monthly. ```APIDOC ## GET /reference_get_cargo_description_list ### Description List cargo descriptions with optional search. Returns predefined descriptions for common cargo types. Cache monthly. ### Method GET ### Endpoint /reference_get_cargo_description_list ### Query Parameters - **Page** (integer) - Optional - Page number for pagination - **Search** (string) - Optional - Search term for cargo descriptions ### Response #### Success Response (200) - **CargoDescriptions** (array) - Array of cargo descriptions - **Ref** (string) - Reference identifier - **Description** (string) - Description text #### Response Example { "CargoDescriptions": [ { "Ref": "desc_001", "Description": "Electronics" } ] } ``` -------------------------------- ### Run Nova Poshta MCP Server Source: https://github.com/shopanaio/carrier-api/blob/main/README.md Starts the Model Context Protocol (MCP) server for integrating Nova Poshta with AI assistants. This command-line interface tool facilitates communication with AI models. ```bash npx @shopana/novaposhta-mcp-server ``` -------------------------------- ### JavaScript Pretty Print Initialization Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/index.html This JavaScript code initializes the 'prettyPrint' function when the window loads. This is commonly used for formatting code examples or output, often in conjunction with libraries like Google's Prettify. ```javascript window.onload = function () { prettyPrint(); }; ``` -------------------------------- ### Complete Type Safety Example Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/README.md Illustrates the benefit of complete type safety in the API client. TypeScript provides precise type definitions for inputs and outputs, enabling autocomplete and compile-time checks for all parameters and response structures. ```typescript // TypeScript knows the exact shape of the response const result = await client.address.searchCities({ FindByString: 'Kyiv', Limit: 10 }); // ^? NovaPoshtaResponse // Autocomplete for all parameters const waybill = await client.waybill.create({ PayerType: '...', // Autocomplete: 'Sender' | 'Recipient' | 'ThirdPerson' PaymentMethod: '...', // Autocomplete: 'Cash' | 'NonCash' // ... all parameters with type checking }); ``` -------------------------------- ### GET /reference_get_service_types Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md List delivery service types. Four core technologies: WarehouseWarehouse, WarehouseDoors, DoorsWarehouse, DoorsDoors. Recommended to cache monthly. ```APIDOC ## GET /reference_get_service_types ### Description List delivery service types. Four core technologies: WarehouseWarehouse, WarehouseDoors, DoorsWarehouse, DoorsDoors. Cache monthly. ### Method GET ### Endpoint /reference_get_service_types ### Response #### Success Response (200) - **ServiceTypes** (array) - Array of available service types - **Ref** (string) - Reference identifier - **Description** (string) - Service type description - **Value** (string) - Service type value #### Response Example { "ServiceTypes": [ { "Ref": "service_001", "Description": "Warehouse to Warehouse", "Value": "WarehouseWarehouse" } ] } ``` -------------------------------- ### Get Service Types in TypeScript Source: https://context7.com/shopanaio/carrier-api/llms.txt This snippet retrieves and displays service types. It calls the appropriate API method to fetch the service types and logs the description and reference of each service type to the console. ```typescript ```typescript const serviceTypes = await client.reference.getServiceTypes(); serviceTypes.data.forEach(type => { console.log(`${type.Description}: ${type.Ref}`); }); // Expected values: // Warehouse - Warehouse: WarehouseWarehouse // Warehouse - Doors: WarehouseDoors // Doors - Warehouse: DoorsWarehouse // Doors - Doors: DoorsDoors ``` ``` -------------------------------- ### Get Cargo Types in TypeScript Source: https://context7.com/shopanaio/carrier-api/llms.txt This snippet demonstrates retrieving cargo types from the API. It fetches a list of available cargo types and iterates through the results, logging the description and reference of each type to the console. ```typescript ```typescript const cargoTypes = await client.reference.getCargoTypes(); cargoTypes.data.forEach(type => { console.log(`${type.Description}: ${type.Ref}`); }); // Expected output: // Parcel: Cargo // Cargo: Cargo // Documents: Documents // Tires and Wheels: TiresWheels // Pallet: Pallet ``` ``` -------------------------------- ### Get Tires and Wheels List - ReferenceService Method Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/referenceService.ts.html Retrieves list of available tires and wheels types from the Nova Poshta API with 24-hour caching. Accepts optional request parameters and returns typed GetTiresWheelsListResponse. ```typescript async getTiresWheelsList(request: GetTiresWheelsListRequest = {}): Promise { const apiRequest: NovaPoshtaRequest = { ...(this.apiKey ? { apiKey: this.apiKey } : {}), modelName: NovaPoshtaModel.Common, calledMethod: NovaPoshtaMethod.GetTiresWheelsList, methodProperties: request as unknown as Record, }; return await this.transport.request(apiRequest); } ``` -------------------------------- ### Get Pack List - ReferenceService Method Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/referenceService.ts.html Retrieves list of available packaging types with optional dimension filters (length, width, height). Results are cached for 24 hours and return a typed GetPackListResponse with packaging options. ```typescript async getPackList(request: GetPackListRequest = {}): Promise { const apiRequest: NovaPoshtaRequest = { ...(this.apiKey ? { apiKey: this.apiKey } : {}), modelName: NovaPoshtaModel.Common, calledMethod: NovaPoshtaMethod.GetPackList, methodProperties: request as unknown as Record, }; return await this.transport.request(apiRequest); } ``` -------------------------------- ### Get Pallets List - ReferenceService Method Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/referenceService.ts.html Retrieves list of available pallets from the Nova Poshta API with 24-hour caching. Accepts optional filter parameters and returns a typed GetPalletsListResponse containing available pallet information. ```typescript async getPalletsList(request: GetPalletsListRequest = {}): Promise { const apiRequest: NovaPoshtaRequest = { ...(this.apiKey ? { apiKey: this.apiKey } : {}), modelName: NovaPoshtaModel.Common, calledMethod: NovaPoshtaMethod.GetPalletsList, methodProperties: request as unknown as Record, }; return await this.transport.request(apiRequest); } ``` -------------------------------- ### Get Delivery Time Intervals in TypeScript Source: https://context7.com/shopanaio/carrier-api/llms.txt This snippet retrieves available delivery time intervals for a specified recipient city and date. It logs the start and end times along with their references, which can be used when creating a waybill. ```typescript ```typescript const intervals = await client.reference.getTimeIntervals({ RecipientCityRef: 'db5c88e0-391c-11dd-90d9-001a92567626', DateTime: '25.12.2024' }); console.log('Available delivery time slots:'); intervals.data.forEach(interval => { console.log(` ${interval.Start} - ${interval.End} (Ref: ${interval.Number})`); }); // Use interval.Number when creating waybill with preferred time ``` ``` -------------------------------- ### Initialize Novaposhta Client with Fetch Transport (TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-transport-fetch/README.md Demonstrates how to create an instance of the Novaposhta API client using the default fetch-based HTTP transport. It requires the client constructor, the transport creator, and essential configuration like API key and base URL. ```typescript import { createClient } from '@shopana/novaposhta-api-client'; import { createFetchHttpTransport } from '@shopana/novaposhta-transport-fetch'; const client = createClient({ transport: createFetchHttpTransport(), baseUrl: 'https://api.novaposhta.ua/v2.0/json/', apiKey: process.env.NP_API_KEY, }); ``` -------------------------------- ### Initialize GitBook Configuration Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/docs/novaposhta-2.0/dovdnik.html Initializes the GitBook environment with custom configuration settings. This includes options for comments, search indexing, social sharing, and font settings. It's a prerequisite for using GitBook features within the project. ```javascript require("gitbook", function(gitbook) { var config = { "comment": {"highlightCommented": true}, "autocover": {}, "highlight": {}, "search": {"maxIndexSize": 1000000}, "sharing": {"facebook": true, "twitter": true, "google": false, "weibo": false, "instapaper": false, "vk": false, "all": ["facebook", "google", "twitter", "weibo", "instapaper"]}, "fontsettings": {"theme": "white", "family": "sans", "size": 2} }; gitbook.start(config); }); ``` -------------------------------- ### GET /waybill_get_delivery_date Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md Get estimated delivery date for a city pair and service type. ```APIDOC ## GET /waybill_get_delivery_date ### Description Get estimated delivery date for a city pair and service type. ### Method GET ### Endpoint /waybill_get_delivery_date ### Query Parameters - **SenderCity** (string) - Required - Sender city reference - **RecipientCity** (string) - Required - Recipient city reference - **ServiceType** (string) - Required - Service type (WarehouseWarehouse, WarehouseDoors, DoorsWarehouse, DoorsDoors) - **DateTime** (string) - Optional - Shipment date in ISO format ### Response #### Success Response (200) - **EstimatedDeliveryDate** (string) - Estimated delivery date - **DeliveryDays** (integer) - Number of days for delivery - **ServiceType** (string) - Service type used for calculation #### Response Example { "EstimatedDeliveryDate": "2024-01-15", "DeliveryDays": 3, "ServiceType": "WarehouseWarehouse" } ``` -------------------------------- ### GET /reference_get_payment_forms Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md Get list of payment forms for waybill creation. Returns Cash/NonCash. Non-cash payments are available only to contracted clients. ```APIDOC ## GET /reference_get_payment_forms ### Description Get list of payment forms for waybill creation. Returns Cash/NonCash. Non-cash payments are available only to contracted clients. Cache monthly. ### Method GET ### Endpoint /reference_get_payment_forms ### Response #### Success Response (200) - **PaymentForms** (array) - Array of payment forms - **Ref** (string) - Reference identifier - **Description** (string) - Payment form description - **Value** (string) - Payment ``` -------------------------------- ### Default Fetch Transport (TypeScript) Source: https://context7.com/shopanaio/carrier-api/llms.txt This code snippet demonstrates the setup of the default fetch transport for making HTTP requests. It imports `createFetchHttpTransport` from the `@shopana/novaposhta-transport-fetch` package and uses it to create a transport instance. The code then uses this transport, along with a base URL and API key, to instantiate the client. ```typescript ```typescript import { createFetchHttpTransport } from '@shopana/novaposhta-transport-fetch'; const transport = createFetchHttpTransport(); const client = createClient({ transport, baseUrl: 'https://api.novaposhta.ua/v2.0/json/', apiKey: process.env.NOVA_POSHTA_API_KEY }); ``` ``` -------------------------------- ### Create Nova Poshta API Client Instance Source: https://context7.com/shopanaio/carrier-api/llms.txt Initializes the Nova Poshta API client with a specified transport layer (e.g., fetch), base URL, and an optional API key. The transport layer handles HTTP communication, and the API key is required for certain operations. ```typescript import { createClient } from '@shopana/novaposhta-api-client'; import { createFetchHttpTransport } from '@shopana/novaposhta-transport-fetch'; const client = createClient({ transport: createFetchHttpTransport(), baseUrl: 'https://api.novaposhta.ua/v2.0/json/', apiKey: process.env.NOVA_POSHTA_API_KEY, // Optional for tracking/reference }); ``` -------------------------------- ### GET /reference_get_time_intervals Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md Get available delivery time intervals for recipient city. Returns Number/Start/End entries. Recommended to cache monthly. ```APIDOC ## GET /reference_get_time_intervals ### Description Get available delivery time intervals for recipient city. Returns Number/Start/End entries. Cache monthly. ### Method GET ### Endpoint /reference_get_time_intervals ### Query Parameters - **CityRef** (string) - Required - City reference identifier ### Response #### Success Response (200) - **DeliveryIntervals** (array) - Array of delivery time windows - **Number** (integer) - Interval number - **Start** (string) - Start time in HH:MM format - **End** (string) - End time in HH:MM format #### Response Example { "DeliveryIntervals": [ { "Number": 1, "Start": "09:00", "End": "13:00" } ] } ``` -------------------------------- ### GET /reference_get_types_of_payers Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md Get list of payer types for waybill creation. Returns Sender/Recipient/ThirdPerson. ThirdPerson payer is accessible only after signing a service contract. ```APIDOC ## GET /reference_get_types_of_payers ### Description Get list of payer types for waybill creation. Returns Sender/Recipient/ThirdPerson. ThirdPerson payer is accessible only after signing a service contract. Cache monthly. ### Method GET ### Endpoint /reference_get_types_of_payers ### Response #### Success Response (200) - **PayerTypes** (array) - Array of available payer types - **Ref** (string) - Reference identifier - **Description** (string) - Payer type description - **Value** (string) - Payer value (Sender/Recipient/ThirdPerson) #### Response Example { "PayerTypes": [ { "Ref": "payer_001", "Description": "Sender", "Value": "Sender" } ] } ``` -------------------------------- ### Configure MCP Server for Nova Poshta Source: https://context7.com/shopanaio/carrier-api/llms.txt This JSON configuration sets up the MCP server for Nova Poshta. It specifies the command to run, arguments, and environment variables including the API key, system name, and log level. ```json { "mcpServers": { "novaposhta": { "command": "npx", "args": ["-y", "-p", "@shopana/novaposhta-mcp-server", "novaposhta-mcp"], "env": { "NOVA_POSHTA_API_KEY": "your_api_key_here", "NOVA_POSHTA_SYSTEM": "DevCentre", "LOG_LEVEL": "info" } } } } ``` -------------------------------- ### Initialize Nova Poshta API Client with Services Source: https://context7.com/shopanaio/carrier-api/llms.txt Sets up a configured Nova Poshta API client with HTTP transport and registers multiple services (Address, Counterparty, Waybill, Tracking). The client is configured with environment-based API credentials and base URL for API v2.0. ```typescript import { createClient, AddressService, CounterpartyService, WaybillService, TrackingService } from '@shopana/novaposhta-api-client'; import { createFetchHttpTransport } from '@shopana/novaposhta-transport-fetch'; const client = createClient({ transport: createFetchHttpTransport(), baseUrl: 'https://api.novaposhta.ua/v2.0/json/', apiKey: process.env.NOVA_POSHTA_API_KEY, }) .use(new AddressService()) .use(new CounterpartyService()) .use(new WaybillService()) .use(new TrackingService()); ``` -------------------------------- ### GET /reference_get_pickup_time_intervals Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md Get available pickup time intervals. Returns time windows when Nova Poshta can pick up packages from sender. Recommended to cache hourly. ```APIDOC ## GET /reference_get_pickup_time_intervals ### Description Get available pickup time intervals. Returns time windows when Nova Poshta can pick up packages from sender. Cache hourly. ### Method GET ### Endpoint /reference_get_pickup_time_intervals ### Response #### Success Response (200) - **TimeIntervals** (array) - Array of available time windows - **Ref** (string) - Reference identifier - **Start** (string) - Start time in HH:MM format - **End** (string) - End time in HH:MM format #### Response Example { "TimeIntervals": [ { "Ref": "interval_001", "Start": "09:00", "End": "12:00" } ] } ``` -------------------------------- ### Instantiate and Use Nova Poshta API Client (TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/README.md Demonstrates how to create an instance of the Nova Poshta API client using the fetch transport. It shows how to add service plugins (Address, Reference, Tracking) and make API calls for searching cities, getting cargo types, and tracking documents. ```typescript import { createClient, AddressService, ReferenceService, TrackingService } from '@shopana/novaposhta-api-client'; import { createFetchHttpTransport } from '@shopana/novaposhta-transport-fetch'; // Create client with plugins const client = createClient({ transport: createFetchHttpTransport(), baseUrl: 'https://api.novaposhta.ua/v2.0/json/', apiKey: process.env.NOVA_POSHTA_API_KEY, }) .use(new AddressService()) .use(new ReferenceService()) .use(new TrackingService()); // Use the namespaced API const cities = await client.address.searchCities({ FindByString: 'Київ', Limit: 10 }); const cargoTypes = await client.reference.getCargoTypes(); const tracking = await client.tracking.trackDocument({ Documents: ['20450123456789'] }); console.log('Found cities:', cities.data.length); console.log('Package status:', tracking.data[0].Status); ``` -------------------------------- ### Implement createClient and use Methods (TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/core/client.ts.html The `createClient` function initializes a client with a given `ClientContext`. The returned client has a `use` method, which allows for registering and attaching pluggable services. The `use` method injects the client context into the service through the `attach` method if it exists and ensures that namespaces are unique. ```TypeScript export function createClient(ctx: ClientContext): Client { const self: any = {} as Client; self.use = function use>(service: S): Client { // Inject context into service if supported if (typeof service.attach === 'function') { service.attach(ctx); } const ns: string | undefined = (service as any).namespace; Iif (!ns || typeof ns !== 'string') { throw new Error('Service must define a string "namespace" property'); } // Attach the service instance under its namespace (no hoisting) Iif (ns in self) { throw new Error(`Namespace already installed on client: ${ns}`); } (self as any)[ns] = service; return self as Client; }; return self as Client; } ``` -------------------------------- ### Plugin Architecture (TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/README.md Explains the plugin architecture, demonstrating how to use services as plugins. This enables the inclusion of only the necessary functionalities, reducing bundle size. Uses `createClient`, `use`, `AddressService`, and `TrackingService`. ```typescript const client = createClient({ transport, baseUrl, apiKey }) .use(new AddressService()) // Only if you need address operations .use(new TrackingService()); // Only if you need tracking // Tree-shaking automatically removes unused services from your bundle ``` -------------------------------- ### Configure MCP Server for AI Assistants (.mcp.json) Source: https://github.com/shopanaio/carrier-api/blob/main/README.md This JSON configuration is added to `.mcp.json` or Claude Desktop config to set up the Nova Poshta MCP server. It specifies the command to run the server and environment variables, such as the API key. This enables interaction with Nova Poshta services through AI assistants for tasks like package tracking and shipping cost calculation. ```json { "mcpServers": { "novaposhta": { "command": "npx", "args": ["-y", "-p", "@shopana/novaposhta-mcp-server", "novaposhta-mcp"], "env": { "NOVA_POSHTA_API_KEY": "your_api_key_here" } } } } ``` -------------------------------- ### Get Backward Delivery Cargo Types from Nova Poshta API Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/referenceService.ts.html Retrieves the list of cargo types applicable for backward delivery services from the Nova Poshta API. This function is cacheable for 24 hours. It constructs the necessary API request parameters and uses the transport service to get the data. Useful for defining what can be sent back. ```typescript async getBackwardDeliveryCargoTypes( request: GetBackwardDeliveryCargoTypesRequest = {}, ): Promise { const apiRequest: NovaPoshtaRequest = { ...(this.apiKey ? { apiKey: this.apiKey } : {}), modelName: NovaPoshtaModel.Common, calledMethod: NovaPoshtaMethod.GetBackwardDeliveryCargoTypes, methodProperties: request as unknown as Record, }; return await this.transport.request(apiRequest); } ``` -------------------------------- ### Get Document Price (Legacy - TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/waybillService.ts.html Legacy method to retrieve the price for a document shipment. This function is deprecated; use `getPrice()` instead. ```typescript async getDocumentPrice(request: PriceCalculationRequest): Promise { return this.getPrice(request); } ``` -------------------------------- ### Search, Create Address (TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/README.md Demonstrates searching for settlements and streets, followed by creating a new address. It uses the `client.address` methods to interact with the API. Requires an initialized client and valid API credentials. ```typescript // Search for a settlement const settlements = await client.address.searchSettlements({ CityName: 'Київ', Page: 1, Limit: 10, }); const settlementRef = settlements.data[0].Ref; // Search for a street const streets = await client.address.searchSettlementStreets({ StreetName: 'Хрещатик', SettlementRef: settlementRef, Limit: 10, }); const streetRef = streets.data[0].Ref; // Create address const address = await client.address.save({ CounterpartyRef: 'counterparty-ref', StreetRef: streetRef, BuildingNumber: '10', Flat: '5', Note: 'Door code: 1234', }); ``` -------------------------------- ### Get Delivery Price (Legacy - TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/waybillService.ts.html Legacy method to retrieve the delivery price for a shipment. This function is deprecated; use `getPrice()` instead. ```typescript async getDeliveryPrice(request: PriceCalculationRequest): Promise { return this.getPrice(request); } ``` -------------------------------- ### Run Carrier API Locally via stdio Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md This command-line interface execution method is suitable for local development and integration with AI assistants. It allows direct interaction with the Carrier API without needing a separate server setup. Ensure the `novaposhta-mcp` executable or `dist/cli.js` script is available in your environment. ```bash novaposhta-mcp # or node dist/cli.js ``` -------------------------------- ### Get Delivery Date (Legacy - TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/waybillService.ts.html Legacy method to retrieve the delivery date for a shipment. This function is deprecated; use `getDeliveryDate()` instead. ```typescript async getDocumentDeliveryDate(request: DeliveryDateRequest): Promise { return this.getDeliveryDate(request); } ``` -------------------------------- ### ReferenceService Class Definition and Initialization Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/services/referenceService.ts.html Defines the ReferenceService class with its namespace, transport, and API key properties. The attach method initializes the HttpTransport and sets the API key. This service is designed to interact with the Nova Poshta API for reference data. ```typescript export class ReferenceService { readonly namespace = 'reference' as const; private transport!: HttpTransport; private apiKey?: string; attach(ctx: ClientContext) { this.transport = toHttpTransport(ctx); this.apiKey = ctx.apiKey; } } ``` -------------------------------- ### Address Discovery: Get Warehouses Source: https://github.com/shopanaio/carrier-api/blob/main/postman/novaposhta-api-client/README.md Retrieve a list of Nova Poshta warehouses. Filter by city, warehouse type, or search string. ```APIDOC ## Address Discovery: Get Warehouses ### Description This endpoint retrieves a list of Nova Poshta warehouses. You can filter warehouses by specifying a city reference, warehouse type reference, or a search string for names or numbers. Pagination is supported via 'Page' and 'Limit' parameters. ### Method POST ### Endpoint `/api/v2/json/` ### Parameters #### Request Body - **modelName** (string) - Required - Should be "Address". - **calledMethod** (string) - Required - Should be "getWarehouses". - **methodProperties** (object) - Required: - **CityRef** (string) - Optional - The reference of the city to search within. - **FindByString** (string) - Optional - A string to search for warehouse names or numbers. - **TypeOfWarehouseRef** (string) - Optional - The reference for the type of warehouse (e.g., 'Warehouse', 'Postomate'). - **Page** (string) - Optional - The page number for pagination. Defaults to '1'. - **Limit** (string) - Optional - The maximum number of results per page. Defaults to '50'. ### Request Example ```json { "modelName": "Address", "calledMethod": "getWarehouses", "methodProperties": { "CityRef": "your_city_ref", "FindByString": "Main Street 10", "TypeOfWarehouseRef": "some_type_ref", "Page": "1", "Limit": "5" } } ``` ### Response #### Success Response (200) - **data** (array) - An array of warehouse objects. - **Ref** (string) - Unique identifier for the warehouse. - **Description** (string) - The name of the warehouse. - **Address** (object) - Details about the warehouse address. - ... (other warehouse-related fields) #### Response Example ```json { "data": [ { "Ref": "some_warehouse_ref", "Description": "Warehouse #5", "Address": { "CityRef": "your_city_ref", "Street": "Main Street", "BuildingNumber": "10" } } ], "success": true, "errors": [], "warnings": [], "info": {}, "messageCodes": {}, "errorCodes": {} } ``` ``` -------------------------------- ### Initialize Nova Poshta Client with Services Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/README.md Create and configure a Nova Poshta API client with plugin-based service registration. The client uses a transport layer for HTTP communication and supports multiple services like Address, Counterparty, Tracking, and Waybill management. ```typescript import { createClient, AddressService, CounterpartyService, ContactPersonService, ReferenceService, TrackingService, WaybillService, } from '@shopana/novaposhta-api-client'; import { createFetchHttpTransport } from '@shopana/novaposhta-transport-fetch'; const client = createClient({ transport: createFetchHttpTransport(), baseUrl: 'https://api.novaposhta.ua/v2.0/json/', apiKey: process.env.NP_API_KEY, }) .use(new AddressService()) .use(new CounterpartyService()) .use(new ContactPersonService()) .use(new ReferenceService()) .use(new TrackingService()) .use(new WaybillService()); ``` -------------------------------- ### GET /reference_get_redelivery_payers Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-mcp-server/README.md List payer types for redelivery. Returns who can pay for backward delivery (Sender/Recipient). Used with return shipments. ```APIDOC ## GET /reference_get_redelivery_payers ### Description List payer types for redelivery. Returns who can pay for backward delivery (Sender/Recipient). Used with return shipments. Cache monthly. ### Method GET ### Endpoint /reference_get_redelivery_payers ### Response #### Success Response (200) - **RedeliveryPayers** (array) - Array of payer types - **Ref** (string) - Reference identifier - **Description** (string) - Payer type description - **Value** (string) - Payer value (Sender/Recipient) #### Response Example { "RedeliveryPayers": [ { "Ref": "payer_001", "Description": "Sender pays for return", "Value": "Sender" } ] } ``` -------------------------------- ### Address Discovery: Get Cities Source: https://github.com/shopanaio/carrier-api/blob/main/postman/novaposhta-api-client/README.md Retrieve a list of cities from the Nova Poshta API. This method supports searching by city name and pagination. ```APIDOC ## Address Discovery: Get Cities ### Description This endpoint allows you to retrieve a list of cities. You can filter results by providing a string to search within city names and control the pagination using 'Page' and 'Limit' parameters. ### Method POST ### Endpoint `/api/v2/json/` ### Parameters #### Request Body - **modelName** (string) - Required - Should be "Address". - **calledMethod** (string) - Required - Should be "getCities". - **methodProperties** (object) - Required: - **FindByString** (string) - Optional - A string to filter cities by name. - **Page** (string) - Optional - The page number for pagination. Defaults to '1'. - **Limit** (string) - Optional - The maximum number of results per page. Defaults to '50'. ### Request Example ```json { "modelName": "Address", "calledMethod": "getCities", "methodProperties": { "FindByString": "Kyiv", "Page": "1", "Limit": "10" } } ``` ### Response #### Success Response (200) - **data** (array) - An array of city objects. - **Ref** (string) - Unique identifier for the city. - **Description** (string) - The name of the city. - **CityID** (string) - Internal city ID. - ... (other city-related fields) #### Response Example ```json { "data": [ { "Ref": "some_city_ref", "Description": "Kyiv", "CityID": "123" } ], "success": true, "errors": [], "warnings": [], "info": {}, "messageCodes": {}, "errorCodes": {} } ``` ``` -------------------------------- ### Get Price Calculation - TypeScript Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/services/waybillService.ts.html Calculates the price for a waybill based on specified parameters. It utilizes the InternetDocument model and GetDocumentPrice method, taking a PriceCalculationRequest and returning a PriceCalculationResponse. ```TypeScript import type { PriceCalculationRequest, PriceCalculationResponse } from '../types/waybill'; import type { NovaPoshtaRequest } from '../types/base'; import { NovaPoshtaModel, NovaPoshtaMethod } from '../types/enums'; // ... inside WaybillService class ... async getPrice(request: PriceCalculationRequest): Promise { const apiRequest: NovaPoshtaRequest = { ...(this.apiKey ? { apiKey: this.apiKey } : {}), modelName: NovaPoshtaModel.InternetDocument, calledMethod: NovaPoshtaMethod.GetDocumentPrice, methodProperties: request as unknown as Record, }; return await this.transport.request(apiRequest); } ``` -------------------------------- ### Get Delivery Date - TypeScript Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/services/waybillService.ts.html Calculates and retrieves the estimated delivery date for a waybill. It uses the InternetDocument model and GetDocumentDeliveryDate method, requiring a DeliveryDateRequest and returning a DeliveryDateResponse. ```TypeScript import type { DeliveryDateRequest, DeliveryDateResponse } from '../types/waybill'; import type { NovaPoshtaRequest } from '../types/base'; import { NovaPoshtaModel, NovaPoshtaMethod } from '../types/enums'; // ... inside WaybillService class ... async getDeliveryDate(request: DeliveryDateRequest): Promise { const apiRequest: NovaPoshtaRequest = { ...(this.apiKey ? { apiKey: this.apiKey } : {}), modelName: NovaPoshtaModel.InternetDocument, calledMethod: NovaPoshtaMethod.GetDocumentDeliveryDate, methodProperties: request as unknown as Record, }; return await this.transport.request(apiRequest); } ``` -------------------------------- ### Available Development Scripts for Carrier API (Bash) Source: https://github.com/shopanaio/carrier-api/blob/main/README.md This collection of bash commands represents the various scripts available for developing and managing the carrier-api project. It includes scripts for running the MCP server in different modes (stdio, http), building the API client and MCP server, running tests with coverage options, and performing code quality checks like linting and formatting. ```bash # Development yarn dev # Watch mode for API client yarn dev:mcp:stdio # Run MCP server in stdio mode yarn dev:mcp:http # Run MCP server in HTTP mode # Building yarn build # Build API client yarn build:mcp # Build MCP server # Testing yarn test # Run all tests yarn test:watch # Run tests in watch mode yarn test:coverage # Generate coverage report yarn test:mcp # Run MCP server tests # Code Quality yarn lint # Lint TypeScript files yarn lint:fix # Fix linting issues yarn format # Format code with Prettier yarn format:check # Check code formatting yarn type-check # Run TypeScript type checking ``` -------------------------------- ### Initialize Reference Service with Nova Poshta API Types Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/coverage/lcov-report/services/referenceService.ts.html Imports and type definitions for the reference service module. Sets up HTTP transport integration and defines request/response types for various reference data operations including cargo types, pallets, packaging materials, tire/wheel information, cargo descriptions, message codes, and service types. ```TypeScript /** * Reference service for Nova Poshta API * Handles all reference data operations */ import type { HttpTransport } from '../http/transport'; import type { ClientContext } from '../core/client'; import { toHttpTransport } from '../core/client'; import type { GetCargoTypesRequest, GetCargoTypesResponse, GetPalletsListRequest, GetPalletsListResponse, GetPackListRequest, GetPackListResponse, GetTiresWheelsListRequest, GetTiresWheelsListResponse, GetCargoDescriptionListRequest, GetCargoDescriptionListResponse, GetMessageCodeTextRequest, GetMessageCodeTextResponse, GetServiceTypesRequest, GetServiceTypesResponse }; ``` -------------------------------- ### Complete Waybill Creation Workflow (TypeScript) Source: https://github.com/shopanaio/carrier-api/blob/main/packages/novaposhta-api-client/README.md Demonstrates the complete workflow for creating a waybill, including creating a recipient, searching for relevant addresses and warehouses, and finally creating the waybill itself. Requires API keys and valid data. ```typescript // 1. Create recipient counterparty const recipient = await client.counterparty.save({ CounterpartyType: 'PrivatePerson', CounterpartyProperty: 'Recipient', FirstName: 'Іван', LastName: 'Петренко', Phone: '380501234567', Email: 'ivan@example.com', }); const recipientRef = recipient.data[0].Ref; // 2. Get contact person (created automatically with counterparty) const recipientContact = recipient.data[0].ContactPerson.data[0].Ref; // 3. Search for recipient city const cities = await client.address.searchSettlements({ CityName: 'Київ', Page: 1, Limit: 1, }); const recipientCityRef = cities.data[0].DeliveryCity; // 4. Search for warehouse in recipient city const warehouses = await client.address.getWarehouses({ CityRef: recipientCityRef, Limit: 1, }); const recipientWarehouseRef = warehouses.data[0].Ref; // 5. Create waybill const waybill = await client.waybill.create({ PayerType: 'Sender', PaymentMethod: 'Cash', DateTime: '25.12.2024', CargoType: 'Parcel', Weight: 1.5, ServiceType: 'WarehouseWarehouse', SeatsAmount: 1, Description: 'Test package', Cost: 1000, CitySender: 'sender-city-ref', // your sender city Sender: 'sender-counterparty-ref', // your sender counterparty SenderAddress: 'sender-warehouse-ref', // your sender warehouse ContactSender: 'sender-contact-ref', // your sender contact SendersPhone: '380671234567', CityRecipient: recipientCityRef, Recipient: recipientRef, RecipientAddress: recipientWarehouseRef, ContactRecipient: recipientContact, RecipientsPhone: '380501234567', }); console.log('Waybill created:', waybill.data[0].IntDocNumber); ```