@myparcel/sdk

Official JavaScript SDK to connect to the MyParcel API via Node.js or browser.
Installation
# Using Yarn
yarn add @myparcel/sdk
# Or NPM
npm i @myparcel/sdk
Endpoints
Public
Public endpoints do not require authorization and are safe to use in a browser.
- Delivery options
- Pickup locations
- Carriers
Private
Private endpoints require an Authorization header. This should be a base64
encoded MyParcel API key. You can create one in the shop settings in
our backoffice. See Authorization in the API documentation for more
information.
Usage examples
Basic usage
The client is Promise-based, so you can use async/await
, or Promise.then
.
First, instantiate an SDK and pass the endpoints you want to use.
import { createPrivateSdk, PostShipments } from '@myparcel/sdk';
const clientConfig = {
headers: {
Authorization: 'bearer ' + MY_BASE_64_ENCODED_API_KEY
}
};
const sdk = createPrivateSdk(new FetchClient(clientConfig), [
new PostShipments(),
]);
Then call the endpoint. There are constants available in our SDK for data like
carriers, package types, delivery types and more.
See constants
const result = await sdk.postShipments({
body: [
{
carrier: 1,
options: {
package_type: 'package',
},
recipient: {
cc: 'NL',
city: 'Hoofddorp',
person: 'Ms. Parcel',
street: 'Antareslaan 31',
},
},
]
});
console.log(result);
Using constants
Our SDK exposes some constants to make working with our API easier.
- Carriers
import { CARRIERS } from '@myparcelnl/sdk';
CARRIERS.POSTNL_NAME
- Package types: Contains all package types' names and IDs.
import { PACKAGE_TYPES } from '@myparcelnl/sdk';
PACKAGE_TYPES.DIGITAL_STAMP_NAME
PACKAGE_TYPES.PACKAGE_ID
PACKAGE_TYPES.LETTER
- Delivery types
import { DELIVERY_TYPES } from '@myparcelnl/sdk';
DELIVERY_TYPES.STANDARD_NAME
DELIVERY_TYPES.PICKUP_ID
DELIVERY_TYPES.MORNING
- Countries: Contains constants for all countries, by name.
import { COUNTRIES } from '@myparcelnl/sdk';
COUNTRIES.NETHERLANDS
COUNTRIES.GERMANY
Creating a new endpoint
To create a new endpoint, you can extend either AbstractPrivateEndpoint
or AbstractPublicEndpoint
and fill in the derived class as needed.
Feel free to add open a pull request to add it to our repository!
See CONTRIBUTING.md.
Creating a new client
In this example we're creating an Axios client.
class AxiosClient extends AbstractClient {
async request(endpoint, options) {
try {
const response = await axios.request({
method: endpoint.method,
url: this.createUrl(endpoint, options),
headers: {
...this.getHeaders(),
...endpoint.getHeaders()
}
});
return response.data;
} catch (e) {
return e.response.data;
}
}
}
Now use the new client with an SDK instance:
const sdk = createPublicSdk(new AxiosClient(), [new GetCarriers()]);
const carriers = await sdk.getCarriers();
console.log(carriers);
Contributing
See CONTRIBUTING.md.