What you need before calling the API
- A FreightMaster customer account: opened online on /en/create-account (business registered outside France) or /inscription (registered in France, form in French), or opened for you by your agency.
- A test key, created in the portal under the “API” menu. It starts with
fm_test_and is shown once; 5 active keys per account at most. - The base URL
https://freightmaster.fr/api/v1, JSON in and out, field names insnake_case, amounts in euros, dates asYYYY-MM-DD(Paris calendar) and ISO 8601 timestamps in UTC. - The key in the
Authorization: Bearerheader, never in the URL. Messages are in French, or in English withAccept-Language: en.
In the examples, the key sits in the FM_KEY variable (export FM_KEY=fm_test_…), never written into the code, and the base URL in FM_BASE, by default https://freightmaster.fr/api/v1. Without writing any code, the portal console, “Try the API”, sends the same requests and shows the responses.
Each step has its curl example, with the other languages folded underneath. The code is the code of the French page, run against the API; comments and messages are translated here. What you need to run them:
- curl: curl; jq for the booking example; openssl for the signature
- JavaScript (Node.js): Node.js 18 or later, as an ES module (.mjs file)
- Python: Python 3 and requests (pip install requests); the signature check uses the standard library alone
- PHP: PHP 8 with the curl extension
- C#: .NET 8, top-level program
1. Check the key
GET /me confirms that the key works and says what it allows: capabilities.can_book tells you whether it can book, limits gives its quotas.
curl -sS "${FM_BASE:-https://freightmaster.fr/api/v1}/me" \
-H "Authorization: Bearer $FM_KEY"{
"object": "account",
"livemode": false,
"key_id": "key_120b745f43056f60",
"account": {
"company": "RECETTE API - ne pas utiliser",
"currency": "EUR",
"vat": {
"regime": "fr_standard",
"rate_percent": 20
}
},
"capabilities": {
"can_quote": true,
"can_book": true
},
"limits": {
"quotes_per_minute": 60,
"quotes_per_day": 2000,
"bookings_per_hour": 20,
"bookings_per_day": 100,
"reads_per_minute": 120
}
}Response recorded before cancellations_per_hour and the account's own ceilings were added to limits; the current shape is in the reference for GET /me.
2. Quote a shipment
POST /quotes takes the origin, the destination and the pallets, and responds 201 with the offers for the route. One or more offers depending on the route and the load: the POST /quotes response is authoritative.
| Field | Required | Content |
|---|---|---|
| origin, destination | Yes | country (2-letter ISO code) and the full postal_: 5 digits in France. France must be the origin or the destination. |
| pallets | Yes | 6 lines at most: quantity (1 to 6, default 1), length_, width_, height_, weight_ (weight of one pallet). The height is required. |
| pickup_date | No | Requested pickup date, YYYY-MM-DD: a business day, the next business day at the earliest, 90 days ahead at most. Default: the next business day. |
| services | No | Booleans delivery_, private_, small_, tail_, europallet_; dangerous_ (UN number), insurance (value to insure), guaranteed_. |
| reference | No | Your reference, 64 characters at most, returned unchanged. |
The API rejects any field it does not know, and checks the gauge before calculating a price: 6 pallets, 2.4 loading metres, 220 cm high, 1,500 kg per pallet. The details are in the API limits.
curl -sS -X POST "${FM_BASE:-https://freightmaster.fr/api/v1}/quotes" \
-H "Authorization: Bearer $FM_KEY" \
-H "Content-Type: application/json" \
-d '{"origin":{"country":"FR","postal_code":"59000"},"destination":{"country":"FR","postal_code":"69003"},"pallets":[{"quantity":1,"length_cm":120,"width_cm":80,"height_cm":150,"weight_kg":300}],"reference":"PO-12345"}'JavaScript (Node.js)
// Node.js 18 or later (built-in fetch). Key in the FM_KEY environment variable.
const BASE = process.env.FM_BASE || 'https://freightmaster.fr/api/v1';
const res = await fetch(`${BASE}/quotes`, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.FM_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
origin: { country: 'FR', postal_code: '59000' },
destination: { country: 'FR', postal_code: '69003' },
pallets: [{ quantity: 1, length_cm: 120, width_cm: 80, height_cm: 150, weight_kg: 300 }],
reference: 'PO-12345',
}),
});
const quote = await res.json();
if (!res.ok) throw new Error(`${quote.code}: ${quote.detail}`);
console.log(JSON.stringify(quote, null, 2));Python
# Python 3 with requests (pip install requests). Key in the FM_KEY environment variable.
import json
import os
import requests
BASE = os.environ.get("FM_BASE", "https://freightmaster.fr/api/v1")
r = requests.post(
f"{BASE}/quotes",
headers={"Authorization": f"Bearer {os.environ['FM_KEY']}"},
json={
"origin": {"country": "FR", "postal_code": "59000"},
"destination": {"country": "FR", "postal_code": "69003"},
"pallets": [{"quantity": 1, "length_cm": 120, "width_cm": 80, "height_cm": 150, "weight_kg": 300}],
"reference": "PO-12345",
},
timeout=30,
)
quote = r.json()
if not r.ok:
raise SystemExit(f"{quote['code']}: {quote['detail']}")
print(json.dumps(quote, indent=2, ensure_ascii=False))PHP
<?php
// PHP 8 with the curl extension. Key in the FM_KEY environment variable.
$base = getenv('FM_BASE') ?: 'https://freightmaster.fr/api/v1';
$ch = curl_init("$base/quotes");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('FM_KEY'), 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'origin' => ['country' => 'FR', 'postal_code' => '59000'],
'destination' => ['country' => 'FR', 'postal_code' => '69003'],
'pallets' => [['quantity' => 1, 'length_cm' => 120, 'width_cm' => 80, 'height_cm' => 150, 'weight_kg' => 300]],
'reference' => 'PO-12345',
]),
]);
$quote = json_decode(curl_exec($ch), true);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) !== 201) {
throw new RuntimeException($quote['code'] . ': ' . $quote['detail']);
}
echo json_encode($quote, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;C#
// .NET 8, top-level program. Key in the FM_KEY environment variable.
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
var baseUrl = Environment.GetEnvironmentVariable("FM_BASE") ?? "https://freightmaster.fr/api/v1";
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("FM_KEY"));
var response = await http.PostAsJsonAsync($"{baseUrl}/quotes", new
{
origin = new { country = "FR", postal_code = "59000" },
destination = new { country = "FR", postal_code = "69003" },
pallets = new[] { new { quantity = 1, length_cm = 120, width_cm = 80, height_cm = 150, weight_kg = 300 } },
reference = "PO-12345",
});
var quote = await response.Content.ReadFromJsonAsync<JsonElement>();
if (!response.IsSuccessStatusCode) throw new Exception($"{quote.GetProperty("code")}: {quote.GetProperty("detail")}");
Console.WriteLine(quote);What the response contains:
quote_idandexpires_at: the quote is valid for 24 hours.pickup_date,routeandshipment: the pickup date used, the route, and the loading metres, weight and volume calculated.offers, in ascending order of price excluding VAT. For each offer:offer_id,carrierandproduct,chargeable_weight_kg(chargeable weight),price(transport, surcharge lines, total excluding VAT, VAT according to the account's regime, total including VAT),notices,bookable, andbooking_url, a link to the website with the route and pallets already filled in.unavailable: when no offer comes back, the reason, with a code explained in the quote refusals.
carrier.id is a stable identifier, for example dhl_freight or xpo: treat it as an open string, as new values can appear.
{
"quote_id": "qt_IpQdszegRUtiV40B",
"object": "quote",
"livemode": false,
"created_at": "2026-11-07T14:56:56.061Z",
"expires_at": "2026-11-08T14:56:56.061Z",
"currency": "EUR",
"reference": "PO-12345",
"pickup_date": "2026-11-09",
"route": {
"origin": {
"country": "FR",
"postal_code": "59000"
},
"destination": {
"country": "FR",
"postal_code": "69003"
}
},
"shipment": {
"pallet_count": 1,
"loading_meters": 0.4,
"actual_weight_kg": 300,
"volume_m3": 1.44
},
"offers": [
{
"offer_id": "of_mesm3XYcp_tu",
"carrier": {
"id": "dhl_freight",
"name": "DHL Freight"
},
"product": {
"id": "dhl_freight.pallet",
"name": "DHL Freight"
},
"chargeable_weight_kg": 300,
"price": {
"transport_excl_vat": 143.33,
"lines": [
{
"code": "fuel",
"label": "Fuel surcharge",
"amount": 23.65,
"rate_percent": 16.5
}
],
"total_excl_vat": 166.98,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 33.4
},
"total_incl_vat": 200.38
},
"notices": [],
"bookable": true
}
],
"unavailable": []
}Show the whole response
{
"quote_id": "qt_IpQdszegRUtiV40B",
"object": "quote",
"livemode": false,
"created_at": "2026-11-07T14:56:56.061Z",
"expires_at": "2026-11-08T14:56:56.061Z",
"currency": "EUR",
"reference": "PO-12345",
"pickup_date": "2026-11-09",
"route": {
"origin": {
"country": "FR",
"postal_code": "59000"
},
"destination": {
"country": "FR",
"postal_code": "69003"
}
},
"shipment": {
"pallet_count": 1,
"loading_meters": 0.4,
"actual_weight_kg": 300,
"volume_m3": 1.44
},
"offers": [
{
"offer_id": "of_mesm3XYcp_tu",
"carrier": {
"id": "dhl_freight",
"name": "DHL Freight"
},
"product": {
"id": "dhl_freight.pallet",
"name": "DHL Freight"
},
"chargeable_weight_kg": 300,
"price": {
"transport_excl_vat": 143.33,
"lines": [
{
"code": "fuel",
"label": "Fuel surcharge",
"amount": 23.65,
"rate_percent": 16.5
}
],
"total_excl_vat": 166.98,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 33.4
},
"total_incl_vat": 200.38
},
"notices": [],
"bookable": true
},
{
"offer_id": "of_swlJ2XeKYVls",
"carrier": {
"id": "xpo",
"name": "XPO"
},
"product": {
"id": "xpo.standard",
"name": "XPO"
},
"chargeable_weight_kg": 300,
"price": {
"transport_excl_vat": 172.7,
"lines": [
{
"code": "fuel",
"label": "Fuel surcharge",
"amount": 31.85,
"rate_percent": 18.44
}
],
"total_excl_vat": 204.55,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 40.91
},
"total_incl_vat": 245.46
},
"notices": [],
"bookable": true
},
{
"offer_id": "of_Clmutm1cWkSo",
"carrier": {
"id": "dgs",
"name": "DGS"
},
"product": {
"id": "dgs.pallet",
"name": "DGS (Palette)"
},
"chargeable_weight_kg": 300,
"price": {
"transport_excl_vat": 226.67,
"lines": [
{
"code": "fuel",
"label": "Fuel surcharge",
"amount": 41.93,
"rate_percent": 18.5
}
],
"total_excl_vat": 268.6,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 53.72
},
"total_incl_vat": 322.32
},
"notices": [],
"bookable": true
},
{
"offer_id": "of_VKnmRc9VhCMw",
"carrier": {
"id": "dgs",
"name": "DGS"
},
"product": {
"id": "dgs.weight",
"name": "DGS (Poids)"
},
"chargeable_weight_kg": 300,
"price": {
"transport_excl_vat": 312.5,
"lines": [
{
"code": "fuel",
"label": "Fuel surcharge",
"amount": 57.81,
"rate_percent": 18.5
}
],
"total_excl_vat": 370.31,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 74.06
},
"total_incl_vat": 444.37
},
"notices": [],
"bookable": true
},
{
"offer_id": "of_WZ02g8-LdlaI",
"carrier": {
"id": "geodis",
"name": "GEODIS"
},
"product": {
"id": "geodis.standard",
"name": "GEODIS"
},
"chargeable_weight_kg": 300,
"price": {
"transport_excl_vat": 419.92,
"lines": [
{
"code": "urban_delivery",
"label": "Restricted urban area delivery",
"amount": 17.33
},
{
"code": "fuel",
"label": "Fuel surcharge",
"amount": 106.65,
"rate_percent": 24.39
}
],
"total_excl_vat": 543.9,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 108.78
},
"total_incl_vat": 652.68
},
"notices": [
{
"code": "urban_delivery_included",
"message": "Restricted urban area delivery: surcharge included."
}
],
"bookable": true
},
{
"offer_id": "of_dq4Q-txDf9S1",
"carrier": {
"id": "france_express",
"name": "France Express"
},
"product": {
"id": "france_express.express",
"name": "France Express"
},
"chargeable_weight_kg": 300,
"price": {
"transport_excl_vat": 809.62,
"lines": [
{
"code": "urban_delivery",
"label": "Restricted urban area delivery",
"amount": 17.33
},
{
"code": "fuel",
"label": "Fuel surcharge",
"amount": 201.69,
"rate_percent": 24.39
}
],
"total_excl_vat": 1028.64,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 205.73
},
"total_incl_vat": 1234.37
},
"notices": [
{
"code": "urban_delivery_included",
"message": "Restricted urban area delivery: surcharge included."
}
],
"bookable": true
}
],
"unavailable": []
}Prices of the test account, recorded on 7 November 2026: your account's prices may differ. Response recorded before the booking_url link was added to each offer.
3. Make a test booking
POST /shipments books an offer from the quote. With a test key, the booking is simulated: no real shipment, no e-mail to the agency. It still moves forward through to delivery: each step reached is published, event and test webhook, when you read the API (GET /events, GET /shipments/{id}, the label) or call advance. The sandbox never publishes shipment.confirmed, nor a change of carrier, date or price.
- The
Idempotency-Keyheader is required: see replay without duplicates. quote_idandoffer_id: the chosen offer. Pallets, services and pickup date come from the quote.shipper:company,contact,phone,email,address,postal_code,city,country, all required.consignee:company,phone,address,postal_code,city,countryrequired,contactandemailoptional.- Countries and postal codes identical to the quote, otherwise
does_not_match_quote. Optional:goods_description,pallet_comments,comments,reference.
# Quote, then book the bookable offer at the top of the list (jq extracts the IDs).
BASE="${FM_BASE:-https://freightmaster.fr/api/v1}"
QUOTE=$(curl -sS -X POST "$BASE/quotes" -H "Authorization: Bearer $FM_KEY" -H "Content-Type: application/json" \
-d '{"origin":{"country":"FR","postal_code":"59000"},"destination":{"country":"FR","postal_code":"69003"},"pallets":[{"quantity":1,"length_cm":120,"width_cm":80,"height_cm":150,"weight_kg":300}],"reference":"PO-12345"}')
QUOTE_ID=$(echo "$QUOTE" | jq -r '.quote_id')
OFFER_ID=$(echo "$QUOTE" | jq -r '[.offers[] | select(.bookable)][0].offer_id')
curl -sS -X POST "$BASE/shipments" \
-H "Authorization: Bearer $FM_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: ${IDEMPOTENCY_KEY:-PO-12345-1}" \
--data @- <<EOF
{
"quote_id": "$QUOTE_ID",
"offer_id": "$OFFER_ID",
"shipper": { "company": "Exemple Expéditeur SAS", "contact": "Claire Martin", "phone": "+33 3 20 00 00 00",
"email": "expedition@exemple.fr", "address": "12 rue Nationale", "postal_code": "59000", "city": "Lille", "country": "FR" },
"consignee": { "company": "Exemple Destinataire SARL", "contact": "Paul Durand", "phone": "+33 4 72 00 00 00",
"address": "8 rue Garibaldi", "postal_code": "69003", "city": "Lyon", "country": "FR" },
"goods_description": "Machine parts on a stretch-wrapped pallet",
"reference": "PO-12345"
}
EOFJavaScript (Node.js)
// Node.js 18 or later. Test key in FM_KEY.
const BASE = process.env.FM_BASE || 'https://freightmaster.fr/api/v1';
const auth = { Authorization: `Bearer ${process.env.FM_KEY}`, 'Content-Type': 'application/json' };
const call = async (path, body, headers = {}) => {
const res = await fetch(`${BASE}${path}`, { method: 'POST', headers: { ...auth, ...headers }, body: JSON.stringify(body) });
const json = await res.json();
if (!res.ok) throw new Error(`${json.code}: ${json.detail}`);
return json;
};
const quote = await call('/quotes', {
origin: { country: 'FR', postal_code: '59000' },
destination: { country: 'FR', postal_code: '69003' },
pallets: [{ quantity: 1, length_cm: 120, width_cm: 80, height_cm: 150, weight_kg: 300 }],
reference: 'PO-12345',
});
const offer = quote.offers.find((o) => o.bookable);
const shipment = await call('/shipments', {
quote_id: quote.quote_id,
offer_id: offer.offer_id,
shipper: { company: 'Exemple Expéditeur SAS', contact: 'Claire Martin', phone: '+33 3 20 00 00 00', email: 'expedition@exemple.fr', address: '12 rue Nationale', postal_code: '59000', city: 'Lille', country: 'FR' },
consignee: { company: 'Exemple Destinataire SARL', contact: 'Paul Durand', phone: '+33 4 72 00 00 00', address: '8 rue Garibaldi', postal_code: '69003', city: 'Lyon', country: 'FR' },
goods_description: 'Machine parts on a stretch-wrapped pallet',
reference: 'PO-12345',
}, { 'Idempotency-Key': process.env.IDEMPOTENCY_KEY || 'PO-12345-1' });
console.log(JSON.stringify(shipment, null, 2));Python
# Python 3 with requests. Test key in FM_KEY.
import json
import os
import requests
BASE = os.environ.get("FM_BASE", "https://freightmaster.fr/api/v1")
AUTH = {"Authorization": f"Bearer {os.environ['FM_KEY']}"}
def call(path, body, headers=None):
r = requests.post(f"{BASE}{path}", headers={**AUTH, **(headers or {})}, json=body, timeout=30)
data = r.json()
if not r.ok:
raise SystemExit(f"{data['code']}: {data['detail']}")
return data
quote = call("/quotes", {
"origin": {"country": "FR", "postal_code": "59000"},
"destination": {"country": "FR", "postal_code": "69003"},
"pallets": [{"quantity": 1, "length_cm": 120, "width_cm": 80, "height_cm": 150, "weight_kg": 300}],
"reference": "PO-12345",
})
offer = next(o for o in quote["offers"] if o["bookable"])
shipment = call("/shipments", {
"quote_id": quote["quote_id"],
"offer_id": offer["offer_id"],
"shipper": {"company": "Exemple Expéditeur SAS", "contact": "Claire Martin", "phone": "+33 3 20 00 00 00",
"email": "expedition@exemple.fr", "address": "12 rue Nationale", "postal_code": "59000", "city": "Lille", "country": "FR"},
"consignee": {"company": "Exemple Destinataire SARL", "contact": "Paul Durand", "phone": "+33 4 72 00 00 00",
"address": "8 rue Garibaldi", "postal_code": "69003", "city": "Lyon", "country": "FR"},
"goods_description": "Machine parts on a stretch-wrapped pallet",
"reference": "PO-12345",
}, {"Idempotency-Key": os.environ.get("IDEMPOTENCY_KEY", "PO-12345-1")})
print(json.dumps(shipment, indent=2, ensure_ascii=False))PHP
<?php
// PHP 8 with curl. Test key in FM_KEY.
$base = getenv('FM_BASE') ?: 'https://freightmaster.fr/api/v1';
function fm_post(string $url, array $body, array $headers = []): array {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array_merge(['Authorization: Bearer ' . getenv('FM_KEY'), 'Content-Type: application/json'], $headers),
CURLOPT_POSTFIELDS => json_encode($body),
]);
$json = json_decode(curl_exec($ch), true);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) >= 400) {
throw new RuntimeException($json['code'] . ': ' . $json['detail']);
}
return $json;
}
$quote = fm_post("$base/quotes", [
'origin' => ['country' => 'FR', 'postal_code' => '59000'],
'destination' => ['country' => 'FR', 'postal_code' => '69003'],
'pallets' => [['quantity' => 1, 'length_cm' => 120, 'width_cm' => 80, 'height_cm' => 150, 'weight_kg' => 300]],
'reference' => 'PO-12345',
]);
$offer = array_values(array_filter($quote['offers'], fn ($o) => $o['bookable']))[0];
$shipment = fm_post("$base/shipments", [
'quote_id' => $quote['quote_id'],
'offer_id' => $offer['offer_id'],
'shipper' => ['company' => 'Exemple Expéditeur SAS', 'contact' => 'Claire Martin', 'phone' => '+33 3 20 00 00 00', 'email' => 'expedition@exemple.fr', 'address' => '12 rue Nationale', 'postal_code' => '59000', 'city' => 'Lille', 'country' => 'FR'],
'consignee' => ['company' => 'Exemple Destinataire SARL', 'contact' => 'Paul Durand', 'phone' => '+33 4 72 00 00 00', 'address' => '8 rue Garibaldi', 'postal_code' => '69003', 'city' => 'Lyon', 'country' => 'FR'],
'goods_description' => 'Machine parts on a stretch-wrapped pallet',
'reference' => 'PO-12345',
], ['Idempotency-Key: ' . (getenv('IDEMPOTENCY_KEY') ?: 'PO-12345-1')]);
echo json_encode($shipment, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;C#
// .NET 8. Test key in FM_KEY.
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
var baseUrl = Environment.GetEnvironmentVariable("FM_BASE") ?? "https://freightmaster.fr/api/v1";
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("FM_KEY"));
async Task<JsonElement> Post(string path, object body, string? idempotencyKey = null)
{
using var request = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}{path}") { Content = JsonContent.Create(body) };
if (idempotencyKey != null) request.Headers.Add("Idempotency-Key", idempotencyKey);
var response = await http.SendAsync(request);
var json = await response.Content.ReadFromJsonAsync<JsonElement>();
if (!response.IsSuccessStatusCode) throw new Exception($"{json.GetProperty("code")}: {json.GetProperty("detail")}");
return json;
}
var quote = await Post("/quotes", new
{
origin = new { country = "FR", postal_code = "59000" },
destination = new { country = "FR", postal_code = "69003" },
pallets = new[] { new { quantity = 1, length_cm = 120, width_cm = 80, height_cm = 150, weight_kg = 300 } },
reference = "PO-12345",
});
var offer = quote.GetProperty("offers").EnumerateArray().First(o => o.GetProperty("bookable").GetBoolean());
var shipment = await Post("/shipments", new
{
quote_id = quote.GetProperty("quote_id").GetString(),
offer_id = offer.GetProperty("offer_id").GetString(),
shipper = new { company = "Exemple Expéditeur SAS", contact = "Claire Martin", phone = "+33 3 20 00 00 00", email = "expedition@exemple.fr", address = "12 rue Nationale", postal_code = "59000", city = "Lille", country = "FR" },
consignee = new { company = "Exemple Destinataire SARL", contact = "Paul Durand", phone = "+33 4 72 00 00 00", address = "8 rue Garibaldi", postal_code = "69003", city = "Lyon", country = "FR" },
goods_description = "Machine parts on a stretch-wrapped pallet",
reference = "PO-12345",
}, Environment.GetEnvironmentVariable("IDEMPOTENCY_KEY") ?? "PO-12345-1");
Console.WriteLine(shipment);Each run creates a new quote: change IDEMPOTENCY_KEY on every run (PO-12345-2, PO-12345-3…), otherwise the API returns 422 idempotency_key_reused for at least 48 hours.
{
"id": "shp_test_c10fc500a6947ea366a67096",
"object": "shipment",
"livemode": false,
"channel": "api",
"reference": "PO-12345",
"status": "booked",
"booked_at": "2026-11-07T15:15:01.923Z",
"updated_at": "2026-11-07T15:15:01.923Z",
"requested_pickup_date": "2026-11-09",
"carrier": {
"id": "dhl_freight",
"name": "DHL Freight"
},
"shipper": {
"company": "Exemple Expéditeur SAS",
"contact": "Claire Martin",
"phone": "+33 3 20 00 00 00",
"email": "expedition@exemple.fr",
"address": "12 rue Nationale",
"postal_code": "59000",
"city": "Lille",
"country": "FR"
},
"consignee": {
"company": "Exemple Destinataire SARL",
"contact": "Paul Durand",
"phone": "+33 4 72 00 00 00",
"email": null,
"address": "8 rue Garibaldi",
"postal_code": "69003",
"city": "Lyon",
"country": "FR"
},
"pallets": [
{
"length_cm": 120,
"width_cm": 80,
"height_cm": 150,
"weight_kg": 300
}
],
"price": {
"total_excl_vat": 166.98,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 33.4
},
"total_incl_vat": 200.38,
"currency": "EUR"
},
"label": {
"status": "pending",
"expected_by": "2026-11-09T11:00:00.000Z"
},
"tracking": {
"status": "pending",
"url": null,
"number": null
}
}The shipment is booked. The label is pending, with expected_by, an indicative time returned by the API, with no commitment. The pickup date is requested, not guaranteed: the business day after the booking at the earliest.
4. Follow the simulated cycle
A test booking moves forward with time, or one step per call to POST /test/shipments/{id}/advance, reserved for test keys. The steps reached are published, event and test webhook, at your next read of the API (GET /events, GET /shipments/{id}, the label) or when you call advance.
| Simulated step | Reached after (published at your next read) | Event |
|---|---|---|
| Booked | Straight away | shipment. |
| Specimen label | 2 minutes | shipment. |
| Dummy tracking link | 3 minutes | shipment. |
| In transit | 5 minutes | shipment. |
| Delivered | 10 minutes | shipment. |
# SHIPMENT_ID: ID of the test booking (shp_test_…).
curl -sS -X POST "${FM_BASE:-https://freightmaster.fr/api/v1}/test/shipments/$SHIPMENT_ID/advance" \
-H "Authorization: Bearer $FM_KEY"Before the label, GET /shipments/{id}/label responds 409 label_not_ready with Retry-After: 60; afterwards, a specimen PDF marked “Document de test” (a test document, not for a real shipment). GET /shipments/{id} gives the state at any time.
# SHIPMENT_ID: ID returned by the booking (shp_…).
curl -sS -o label.pdf -w "HTTP %{http_code}\n" \
"${FM_BASE:-https://freightmaster.fr/api/v1}/shipments/$SHIPMENT_ID/label" \
-H "Authorization: Bearer $FM_KEY"
# HTTP 200: label.pdf is the label. HTTP 409: not ready yet, the file holds the error (Retry-After in seconds).JavaScript (Node.js)
// Node.js 18 or later. SHIPMENT_ID: ID returned by the booking.
import { writeFile } from 'node:fs/promises';
const BASE = process.env.FM_BASE || 'https://freightmaster.fr/api/v1';
const res = await fetch(`${BASE}/shipments/${process.env.SHIPMENT_ID}/label`, {
headers: { Authorization: `Bearer ${process.env.FM_KEY}` },
});
if (res.status === 409) {
const err = await res.json();
console.log(`${err.code}: retry in ${res.headers.get('retry-after')} s`);
} else if (!res.ok) {
const err = await res.json();
throw new Error(`${err.code}: ${err.detail}`);
} else {
await writeFile('label.pdf', Buffer.from(await res.arrayBuffer()));
console.log('label.pdf saved');
}Python
# Python 3 with requests. SHIPMENT_ID: ID returned by the booking.
import os
import requests
BASE = os.environ.get("FM_BASE", "https://freightmaster.fr/api/v1")
r = requests.get(
f"{BASE}/shipments/{os.environ['SHIPMENT_ID']}/label",
headers={"Authorization": f"Bearer {os.environ['FM_KEY']}"},
timeout=30,
)
if r.status_code == 409:
print(f"{r.json()['code']}: retry in {r.headers.get('Retry-After')} s")
elif not r.ok:
raise SystemExit(f"{r.json()['code']}: {r.json()['detail']}")
else:
with open("label.pdf", "wb") as f:
f.write(r.content)
print("label.pdf saved")PHP
<?php
// PHP 8 with curl. SHIPMENT_ID: ID returned by the booking.
$base = getenv('FM_BASE') ?: 'https://freightmaster.fr/api/v1';
$ch = curl_init("$base/shipments/" . getenv('SHIPMENT_ID') . '/label');
$retryAfter = null;
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('FM_KEY')],
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
if (stripos($line, 'Retry-After:') === 0) { $retryAfter = trim(substr($line, 12)); }
return strlen($line);
},
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status === 409) {
echo json_decode($body, true)['code'] . ": retry in $retryAfter s", PHP_EOL;
} elseif ($status >= 400) {
$err = json_decode($body, true);
throw new RuntimeException($err['code'] . ': ' . $err['detail']);
} else {
file_put_contents('label.pdf', $body);
echo 'label.pdf saved', PHP_EOL;
}C#
// .NET 8. SHIPMENT_ID: ID returned by the booking.
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
var baseUrl = Environment.GetEnvironmentVariable("FM_BASE") ?? "https://freightmaster.fr/api/v1";
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("FM_KEY"));
var response = await http.GetAsync($"{baseUrl}/shipments/{Environment.GetEnvironmentVariable("SHIPMENT_ID")}/label");
if (response.StatusCode == HttpStatusCode.Conflict)
{
var err = await response.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine($"{err.GetProperty("code")}: retry in {response.Headers.RetryAfter?.Delta?.TotalSeconds} s");
}
else if (!response.IsSuccessStatusCode)
{
var err = await response.Content.ReadFromJsonAsync<JsonElement>();
throw new Exception($"{err.GetProperty("code")}: {err.GetProperty("detail")}");
}
else
{
await File.WriteAllBytesAsync("label.pdf", await response.Content.ReadAsByteArrayAsync());
Console.WriteLine("label.pdf saved");
}HTTP/1.1 409 Conflict
Content-Type: application/problem+json; charset=utf-8
Retry-After: 60
{
"type": "https://freightmaster.fr/api/erreurs#label_not_ready",
"title": "Conflict",
"status": 409,
"code": "label_not_ready",
"detail": "The label is not available yet. It is attached by the agency after booking.",
"request_id": "req_94b9e691089e544d"
}In production, the label arrives when your agency attaches it, with no guaranteed time, and sometimes never, when the carrier brings its own: label.status then changes to not_provided. The sandbox does not simulate this case. The details: labels, tracking and webhooks.
5. Read the events
GET /events lists the changes in order: each event has a type, an increasing sequence number and the full state of the shipment in data.shipment. Pass the last number processed in after, then store next_cursor; call again while has_more is true.
# FM_CURSOR: sequence of the last event already read (0 at the start).
curl -sS "${FM_BASE:-https://freightmaster.fr/api/v1}/events?after=${FM_CURSOR:-0}&limit=50" \
-H "Authorization: Bearer $FM_KEY"JavaScript (Node.js)
// Node.js 18 or later. FM_CURSOR: sequence of the last event already read (0 at the start).
const BASE = process.env.FM_BASE || 'https://freightmaster.fr/api/v1';
const after = process.env.FM_CURSOR || '0';
const res = await fetch(`${BASE}/events?after=${after}&limit=50`, {
headers: { Authorization: `Bearer ${process.env.FM_KEY}` },
});
const page = await res.json();
if (!res.ok) throw new Error(`${page.code}: ${page.detail}`);
// Process page.data in order, then store page.next_cursor (one cursor per mode).
console.log(JSON.stringify(page, null, 2));Python
# Python 3 with requests. FM_CURSOR: sequence of the last event already read (0 at the start).
import json
import os
import requests
BASE = os.environ.get("FM_BASE", "https://freightmaster.fr/api/v1")
r = requests.get(
f"{BASE}/events",
params={"after": os.environ.get("FM_CURSOR", "0"), "limit": 50},
headers={"Authorization": f"Bearer {os.environ['FM_KEY']}"},
timeout=30,
)
page = r.json()
if not r.ok:
raise SystemExit(f"{page['code']}: {page['detail']}")
# Process page["data"] in order, then store page["next_cursor"] (one cursor per mode).
print(json.dumps(page, indent=2, ensure_ascii=False))PHP
<?php
// PHP 8 with curl. FM_CURSOR: sequence of the last event already read (0 at the start).
$base = getenv('FM_BASE') ?: 'https://freightmaster.fr/api/v1';
$after = getenv('FM_CURSOR') ?: '0';
$ch = curl_init("$base/events?after=$after&limit=50");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('FM_KEY')],
]);
$page = json_decode(curl_exec($ch), true);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) !== 200) {
throw new RuntimeException($page['code'] . ': ' . $page['detail']);
}
// Process $page['data'] in order, then store $page['next_cursor'] (one cursor per mode).
echo json_encode($page, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;C#
// .NET 8. FM_CURSOR: sequence of the last event already read (0 at the start).
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
var baseUrl = Environment.GetEnvironmentVariable("FM_BASE") ?? "https://freightmaster.fr/api/v1";
var after = Environment.GetEnvironmentVariable("FM_CURSOR") ?? "0";
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("FM_KEY"));
var response = await http.GetAsync($"{baseUrl}/events?after={after}&limit=50");
var page = await response.Content.ReadFromJsonAsync<JsonElement>();
if (!response.IsSuccessStatusCode) throw new Exception($"{page.GetProperty("code")}: {page.GetProperty("detail")}");
// Process page.data in order, then store page.next_cursor (one cursor per mode).
Console.WriteLine(page);{
"id": "evt_shp_test_c10fc500a6947ea366a67096.label_available",
"object": "event",
"type": "shipment.label_available",
"sequence": 153,
"created_at": "2026-11-07T15:15:03.450Z",
"livemode": false,
"data": {
"shipment": {
"id": "shp_test_c10fc500a6947ea366a67096",
"object": "shipment",
"livemode": false,
"channel": "api",
"reference": "PO-12345",
"status": "booked",
"booked_at": "2026-11-07T15:15:01.923Z",
"updated_at": "2026-11-07T15:15:01.923Z",
"requested_pickup_date": "2026-11-09",
"carrier": {
"id": "dhl_freight",
"name": "DHL Freight"
},
"shipper": {
"company": "Exemple Expéditeur SAS",
"contact": "Claire Martin",
"phone": "+33 3 20 00 00 00",
"email": "expedition@exemple.fr",
"address": "12 rue Nationale",
"postal_code": "59000",
"city": "Lille",
"country": "FR"
},
"consignee": {
"company": "Exemple Destinataire SARL",
"contact": "Paul Durand",
"phone": "+33 4 72 00 00 00",
"email": null,
"address": "8 rue Garibaldi",
"postal_code": "69003",
"city": "Lyon",
"country": "FR"
},
"pallets": [
{
"length_cm": 120,
"width_cm": 80,
"height_cm": 150,
"weight_kg": 300
}
],
"price": {
"total_excl_vat": 166.98,
"vat": {
"regime": "fr_standard",
"rate_percent": 20,
"amount": 33.4
},
"total_incl_vat": 200.38,
"currency": "EUR"
},
"label": {
"status": "available",
"format": "pdf",
"downloadable": true,
"url": "https://freightmaster.fr/api/v1/shipments/shp_test_c10fc500a6947ea366a67096/label",
"version": 1,
"specimen": true
},
"tracking": {
"status": "pending",
"url": null,
"number": null
}
}
}
}- One cursor per mode. Test and production sequence numbers are separate. Keep two cursors; with the production key, start from
after=0. - The same event can arrive twice, for example by webhook and then through
GET /events: ignore anidyou have already processed. - The filter
types=shipment.label_available,shipment.deliverednarrows the list, butnext_cursorstill moves past the events left out. - The live stream covers every shipment of the account, those booked on the portal included (field
channel). Events can be read for 90 days in production and 30 days in test.
To be notified without polling the API: signed webhooks, up to 3 HTTPS endpoints per account, set up in the portal, each in test or production mode. GET /events remains the way to catch up on everything.
Verify a webhook signature
Each delivery carries the header FreightMaster-Signature: t=…,v1=…: v1 is the HMAC-SHA256, keyed with the endpoint's whsec_… secret, of the text t.body, where body is the raw body received. Compute it on the raw body, compare in constant time and reject a t timestamp older than 5 minutes.
# Shell and openssl. FM_SIGNATURE: header value; FM_BODY_FILE: raw body received; FM_WEBHOOK_SECRET: whsec_…
t=${FM_SIGNATURE#t=}; t=${t%%,*}
v1=${FM_SIGNATURE##*v1=}
expected=$( { printf '%s.' "$t"; cat "$FM_BODY_FILE"; } | openssl dgst -sha256 -hmac "$FM_WEBHOOK_SECRET" -r | cut -d' ' -f1)
age=$(( $(date +%s) - t ))
if [ "$expected" = "$v1" ] && [ "${age#-}" -le 300 ]; then echo valid; else echo invalid; fiJavaScript (Node.js)
// Node.js. Verify BEFORE parsing the JSON: the signature covers the raw body.
import { createHmac, timingSafeEqual } from 'node:crypto';
import { readFileSync } from 'node:fs';
function verifyFreightMasterSignature(header, rawBody, secret, toleranceSec = 300) {
const parts = Object.fromEntries(String(header).split(',').map((p) => p.trim().split('=')));
const t = Number(parts.t);
if (!Number.isFinite(t) || !parts.v1) return false;
if (Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;
const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest();
const received = Buffer.from(parts.v1, 'hex');
return received.length === expected.length && timingSafeEqual(received, expected);
}
const rawBody = readFileSync(process.env.FM_BODY_FILE, 'utf8');
console.log(verifyFreightMasterSignature(process.env.FM_SIGNATURE, rawBody, process.env.FM_WEBHOOK_SECRET) ? 'valid' : 'invalid');Python
# Python 3, standard library. Verify BEFORE parsing the JSON: the signature covers the raw body.
import hashlib
import hmac
import os
import time
def verify_freightmaster_signature(header, raw_body, secret, tolerance_sec=300):
parts = dict(p.strip().split("=", 1) for p in header.split(",") if "=" in p)
try:
t = int(parts["t"])
except (KeyError, ValueError):
return False
if abs(time.time() - t) > tolerance_sec:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, parts.get("v1", ""))
with open(os.environ["FM_BODY_FILE"], "rb") as f:
raw = f.read()
print("valid" if verify_freightmaster_signature(os.environ["FM_SIGNATURE"], raw, os.environ["FM_WEBHOOK_SECRET"]) else "invalid")PHP
<?php
// PHP 8. Verify BEFORE parsing the JSON: the signature covers the raw body (file_get_contents('php://input')).
function verify_freightmaster_signature(string $header, string $rawBody, string $secret, int $toleranceSec = 300): bool {
$parts = [];
foreach (explode(',', $header) as $p) {
[$k, $v] = array_pad(explode('=', trim($p), 2), 2, '');
$parts[$k] = $v;
}
if (!isset($parts['t'], $parts['v1']) || !ctype_digit($parts['t'])) { return false; }
if (abs(time() - (int) $parts['t']) > $toleranceSec) { return false; }
$expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret);
return hash_equals($expected, $parts['v1']);
}
$raw = file_get_contents(getenv('FM_BODY_FILE'));
echo verify_freightmaster_signature(getenv('FM_SIGNATURE'), $raw, getenv('FM_WEBHOOK_SECRET')) ? 'valid' : 'invalid', PHP_EOL;C#
// .NET 8. Verify BEFORE parsing the JSON: the signature covers the raw body.
using System.Security.Cryptography;
using System.Text;
static bool VerifyFreightMasterSignature(string header, string rawBody, string secret, int toleranceSec = 300)
{
var parts = header.Split(',').Select(p => p.Trim().Split('=', 2)).Where(p => p.Length == 2).ToDictionary(p => p[0], p => p[1]);
if (!parts.TryGetValue("t", out var t) || !long.TryParse(t, out var ts) || !parts.TryGetValue("v1", out var v1)) return false;
if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - ts) > toleranceSec) return false;
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
var expected = Convert.ToHexString(hmac.ComputeHash(Encoding.UTF8.GetBytes($"{t}.{rawBody}"))).ToLowerInvariant();
return CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(v1));
}
var raw = File.ReadAllText(Environment.GetEnvironmentVariable("FM_BODY_FILE")!);
Console.WriteLine(VerifyFreightMasterSignature(Environment.GetEnvironmentVariable("FM_SIGNATURE")!, raw, Environment.GetEnvironmentVariable("FM_WEBHOOK_SECRET")!) ? "valid" : "invalid");Replay without duplicates: the idempotency key
Each POST /shipments carries an Idempotency-Key header: 8 to 255 printable ASCII characters, no spaces. The API keeps it for at least 48 hours.
- Same key, same body: the API returns the original response, with the header
Idempotent-Replayed: true, and makes no new booking. That is what to do after a network failure. - Same key, different body:
422 idempotency_key_reused. - A key serves one booking. Use your order number followed by an attempt number,
PO-12345-1, and move on toPO-12345-2to book the same order again after a confirmed cancellation. With the old key, the API returns the original response or refuses (idempotency_key_reused): it does not book. In the sandbox, this protection lasts as long as the key is remembered: after that, an old key with a new quote creates a new simulated booking.
Cancel
POST /shipments/{id}/cancel, with an optional reason in reason.
# SHIPMENT_ID: ID returned by the booking (shp_…).
curl -sS -X POST "${FM_BASE:-https://freightmaster.fr/api/v1}/shipments/$SHIPMENT_ID/cancel" \
-H "Authorization: Bearer $FM_KEY" \
-H "Content-Type: application/json" \
-d '{ "reason": "Order cancelled by the customer" }'- Before the label is attached:
200, the shipment changes tocancelledand theshipment.cancelledevent goes out. - Label already attached:
202, with{ "object": "cancellation", "status": "requested" }. The request goes to your agency, which cancels with the carrier; the status does not change until it has handled it, andGET /shipments/{id}showscancellation. - In transit or delivered:
409 cannot_cancel; already cancelled:409 already_cancelled. - In test, the specimen label arrives after 2 minutes: a later cancellation therefore responds
202.
Go live
- Make at least one test booking, the way your software will.
- In the portal, under the “API” menu, click “Request the production key”. Your agency receives your latest test booking and reviews it; you are told by e-mail when the key is authorised. One request per 24 hours.
- Create the
fm_live_key, shown once, and replace the test key in your software. Bookings become real: sent to your agency and invoiced like those made on the portal. - Quote again with the production key: a test quote cannot be booked in production. Keep a separate event cursor, starting from
after=0.
Three conditions, checked on every real booking: a monthly-invoiced account (otherwise booking_not_allowed), an agency open to API booking (otherwise agency_not_enrolled), and a test booking reviewed (otherwise live_key_requires_review). GET /me tells you in advance with can_book and booking_blocked_reason. Default ceiling: 10 bookings per day and 60 per month, which can be raised on request, through your agency.
When an error occurs
An error responds with an RFC 9457 object carrying a stable code, for example validation_failed and the list of faulty fields. Every code, its cause and what to do: the API errors. Every endpoint and every field: the endpoint documentation. The French version of this page: /api/demarrage.