Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@myparcel/js-sdk

Package Overview
Dependencies
Maintainers
4
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@myparcel/js-sdk

SDK for the MyParcel API, in JavaScript.

  • 2.0.3
  • latest
  • npm
  • Socket score

Version published
Maintainers
4
Created
Source

Content

Installation

npm install @myparcel/js-sdk
yarn add @myparcel/js-sdk

The MyParcel SDK should work with node version >= 8

Git hooks

This repository uses git hooks with Husky.

pre-commit

Runs npm run build before committing and adds the dist folder to the commit you are making.

Use --no-verify with git commit to skip this hook, if needed.

To use this hook while committing from PhpStorm you must have "Run git hooks" checked in the commit dialog. Uncheck it to skip the hook.

Quick start

import Client from '@myparcel/js-sdk';

const client = new Client('api_key_from_MyParcel_backoffice');

// Create one or more new shipments
const ids = await client.shipment.create(shipmentObj);

// Update one or more shipments
const shipments = await client.shipment.update(shipmentObj);

// Delete one or more shipments
await client.shipment.delete(shipmentIds);

// Retrieve multiple shipments
const shipments = await client.shipment.search(queryObj);

// Retrieve a single shipment
const shipment = await client.shipment.get(shipmentId);

Constructor options

NameTypeDescription
keystringOptional. An api key of your account.
acceptLanguagestringOptional. Set to negotiate the response language.

Endpoints

EndpointSupported methodsKey requiredAPI Reference
shipmentcreate, update, delete, get, searchYeshttps://myparcelnl.github.io/api/#6_A
deliverysearchNohttps://myparcelnl.github.io/api/#9_A
pickupsearchNohttps://myparcelnl.github.io/api/#9_B
labelcreateYeshttps://myparcelnl.github.io/api/#6_F
tracktraceget, searchYeshttps://myparcelnl.github.io/api/#6_G

Endpoint methods

Every method is async.

SignatureDescriptionReturns
create({ /* resource data */ })Create a single resource.An array of integer ids.
create([ /* resource objects */ ])Create multiple resources.An array of integer ids.
update({ /* resource data */ })Update a single resource.An array of objects.
update([ /* resource objects */ ])Update multiple resources.An array of objects.
delete(id)Delete one resource.null.
delete([ /* ids */ ])Delete multiple resources.null.
get(id)Retrieve a single resource.An object.
search({ /* filter data */ })Retrieves multiple instances.An array of objects.

Constants

We defined a large set of constant values suitable to help to build the payload.

CategoryLabelDescription
shipmentsCarrierIdsCarrier ID's
shipmentsContent TypesSet of content types.
shipmentsDelivery TypesSet of deliveries.
shipmentsEPS CountriesEuropean countries.
shipmentsMultiCollo CountriesCountries which support shipment with multiple packages.
shipmentsPackage TypesSet of define parcels.
shipmentsRegionsRegions (EU / ROW / Home Country)
shipmentsShipment TypesTypes to define the shipment.
shipmentsDelivery StatussesDifferent states for indication the delivery status.
labelsPaper TypesDifferent set of Paper formats.
labelsPrint PositionsDirections of the pinting positions.

Countries ISO2

A list of all countries over the world with their ISO-2 code.

Examples

For more examples, see the API docs

Create a domestic shipment

import Client from '@myparcel/js-sdk';
import {POSTNL} from '@myparcel-sdk/dist/constant/shipment/carrier-id'
import {PARCEL} from '@myparcel-sdk/dist/constant/shipment/package-type'

const client = new Client('api_key_from_MyParcel_backoffice');

const createShipment = async () => {
    return await client.shipment.create({
        "carrier": POSTNL,
        "reference_identifier" : "FOO-222-BAR-42",
        "recipient": {
            "cc": "NL",
            "region": "Zuid-Holland",
            "city": "Hoofddorp",
            "street": "Siriusdreef",
            "number": "66",
            "postal_code": "2132WT",
            "person": "Mr. Parcel",
            "phone": "0213030315",
            "email": "testing@myparcel.nl"
        },
        "options": {
            "package_type": PARCEL,
            "only_recipient": 1,
            "signature": 1,
            "return": 1,
            "insurance": {
                "amount": 50000,
                "currency": "EUR"
            },
            "large_format": 0,
            "label_description": "My custom description",
            "age_check":1
        },
    })
}
createShipment().then(
    (result) => console.log('Success!\n\n', result),
    (error) => console.error('Something went wrong\n\n', error),
);

Create an international shipment

import Client from '@myparcel/js-sdk';
import {POSTNL} from '@myparcel-sdk/dist/constant/shipment/carrier-id'
import {PARCEL} from '@myparcel-sdk/dist/constant/shipment/package-type'

const client = new Client('api_key_from_MyParcel_backoffice');

const createShipment = async () => {
    return await client.shipment.create({
        "carrier": POSTNL,
        "recipient": {
            "cc": "JP",
            "region": "埼玉県",
            "city": "さいたま市",
            "street": "埼玉県さいたま市浦和区 常盤9-21-21",
            "person": "Tanaka san",
            "company": "さいたま国際キリスト教会",
            "email": "saitamakyokai@gmail.com",
            "phone": "0081-48-825-6637"
        },
        "options": {
            "package_type": PARCEL
        },
        "customs_declaration": {
            "contents": 1,
            "invoice": "1231235345345",
            "weight": 30,
            "items": [{
                "description": "Sample Product",
                "amount": 10,
                "weight": 20,
                "item_value": {
                    "amount": 7000,
                    "currency": "EUR"
                },
                "classification": "0181",
                "country": "NL"
            }, {
                "description": "Sample Product 2",
                "amount": 5,
                "weight": 10,
                "item_value": {
                    "amount": 1000,
                    "currency": "EUR"
                },
                "classification": "0181",
                "country": "BE"
            }]
        },
        "physical_properties": {
            "weight": 30
        }
    });
}
createShipment().then(
    (result) => console.log('Success!\n\n', result),
    (error) => console.error('Something went wrong\n\n', error),
);

Retrieve delivery types and pickup locations

import Client from '@myparcel/js-sdk';

const client = new Client('api_key_from_MyParcel_backoffice');

const deliveryTypes = await client.delivery.search({
    // see https://myparcelnl.github.io/api/#8_A_2 for all filters
    cc: 'NL',
    postal_code: '2132WT',
    number: '66'
});

const pickupLocations = await client.pickup.search({
    // see https://myparcelnl.github.io/api/#8_A_2 for all filters
    cc: 'NL',
    postal_code: '2132WT',
    number: '66'
});

Create a shipment with a pickup location

import Client from '@myparcel/js-sdk';
import {POSTNL} from '@myparcel-sdk/dist/constant/shipment/carrier-id';
import {PARCEL} from '@myparcel-sdk/dist/constant/shipment/package-type';
import {PICKUP} from '@myparcel-sdk/dist/constant/shipment/delivery-type';

const client = new Client('api_key_from_MyParcel_backoffice');

const pickupLocations = await client.pickup.search({
    // see https://myparcelnl.github.io/api/#8_A_2 for all filters
    cc: 'NL',
    postal_code: '2132WT',
    number: '66'
});

/**
* Transform a pickup information object to a shipment pickup.
*
* @param {object} pickup
* @returns {object}
*/
const makeShipmentPickup = ({postal_code, street, city, number, location_name}) => ({postal_code, street, city, number, location_name});

const [id] = await client.shipment.create({
    "carrier": POSTNL,
    "reference_identifier" : "FOO-222-BAR-42",
    "recipient": {
        "cc": "NL",
        "region": "Zuid-Holland",
        "city": "Hoofddorp",
        "street": "Siriusdreef",
        "number": "66",
        "postal_code": "2132WT",
        "person": "Mr. Parcel",
        "phone": "0213030315",
        "email": "testing@myparcel.nl"
    },
    "options": {
        "package_type": PARCEL,
        "delivery_type": PICKUP,
        "only_recipient": 1,
        "signature": 1,
        "return": 1,
        "insurance": {
            "amount": 50000,
            "currency": "EUR"
        },
        "large_format": 0,
        "label_description": "My custom description",
        "age_check":1
    },
    "pickup": makeShipmentPickup(pickupLocations[0]),
});

Download a label

import Client from '@myparcel/js-sdk';
import {A4} from '@myparcel/js-sdk/dist/constant/label/paper-type';
import fetch from 'node-fetch';
import fs from 'fs';

const client = new Client('api_key_from_MyParcel_backoffice');

// Ask the api to create a label for the given ids.
const [{url}] = await client.label.create({
    // See https://myparcelnl.github.io/api/#6_F_3 for all parameters
    ids: [
      // Add your shipment ids
    ],
    format: A4,
});

// The label might not be available for download right away. This could be because
// the requested label is very large, or one of the partners takes a while to respond.

while (true) {
    const response = await fetch(url);

    if (response.status !== 200) {
      // If the label is not available (yet), wait for a bit and try again
      // We strongly recommend that the retry code has sensible retry limits,
      // both in timeout and attempts.
      if (response.status === 404) {
        await new Promise(resolve => setTimeout(resolve, 500));
        continue;
      } else {
        // Something went wrong, stop retrying.
        break;
      }
    }

    // The label is now ready to use. For example, write it to file or send it to the client.
    const file = fs.createWriteStream('myparcel-label.pdf');
    response.body.pipe(file);
}

Contribute

  1. Check for open issues or open a new issue to start a discussion around a bug or feature.
  2. Fork the repository on GitHub to start making your changes.
  3. Write one or more tests for the new feature or that expose the bug.
  4. Make code changes to implement the feature or fix the bug.
  5. Send a pull request to get your changes merged and published.

FAQs

Package last updated on 05 Mar 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc