Get API access
Tell us about your data and volume. Our team replies to your work email.
Calculates the CO₂ of a whole port call and separates the necessary part (berthing and cargo operations) from the avoidable part (waiting for a berth and idling after cargo operations). Input follows the open industry standard for port-call data, so timestamps from any compliant system can be sent as they are. The calculation, factors and results are Switch's own.
Authorizations
AuthorizationBearerrequiredYour API key.Body
Standard format shown here. The simple format, for systems that do not use the standard, is described in Standard port-call data.
Show 3 child attributesHide child attributes
SGSIN.Show 1 child attributeHide child attributes
Show 4 child attributesHide child attributes
BERTH, ANCHORAGE or CARGO_OPERATIONS. Other standard service types are accepted and stored but not used in the calculation.ARRI, DEPA, STRT or CMPL.EST, REQ, PLN or ACT.Show 2 child attributesHide child attributes
missing_field.HFO (default), VLSFO, MGO or LNG. The result names the fuel factor that was applied.Show 1 child attributeHide child attributes
Required timestamps: berth arrival planned (or estimated), berth arrival actual, cargo operations start and completion, and berth departure actual. Anchorage start and completion are optional and improve the waiting figure.
Each request creates a new result with a new id, also when the same portCallID is sent again. Earlier results are kept unchanged. To build one result from timestamps as they arrive, use Push a timestamp.
Response
200: the calculated result. For errors see Errors.
Show 4 child attributesHide child attributes
valid.standard or simple.anchorage_actual or berth_arrival_actual_minus_planned.warnings[] on shipments.waiting_hours, berthing_hours, cargo_ops_hours, idle_hours, total_hours.Show 2 child attributesHide child attributes
hours, fuel_t and co2_t, in hours and metric tonnes.value, unit and source.baseline_idle_hours, excess_idle_hours, fuel_t, co2_t, share_of_avoidable and share_of_total (fractions from 0 to 1).Each figure is rounded on its own, so parts can differ from the total by 0.01. Port-call results are estimates of tank-to-wake CO₂ for the vessel while in port. Send vessel_profile.aux_burn_rate_tph unless Switch has set a vessel profile on your account. See How port-call emissions are split.
Returns a stored result exactly as it was calculated, including the factor versions used at that time. Use it for audit trails and for reports. For a real-time port call, it returns the latest running result until emission.finalized, then the locked result.
Authorizations
AuthorizationBearerrequiredYour API key.Path parameters
emi_3Pc8vR2tY6.Response
200: the response has the same shape as the original shipment or port-call response. 404 not_found: no result exists with that ID.
Calculates emissions (CO₂e) for a container shipment with a published factor for each leg, as well-to-wake by default. Send one leg per transport segment. The response splits the result per leg and per TEU, and names the factor used for each leg.
Authorizations
AuthorizationBearerrequiredYour API key.Body
null, which is treated as not sent.Show 4 child attributesHide child attributes
1 for a 20 ft, 2 for a 40 ft, 2.25 for a 45 ft container. Above 0 and at most 10. Used for the per-TEU result.false.Show 8 child attributesHide child attributes
sea, road or rail.Show 1 child attributeHide child attributes
CNSHA.Show 1 child attributeHide child attributes
distance_source: calculated. Required for road and rail legs.Show 2 child attributesHide child attributes
artic_33t_plus (default), artic_3.5_33t, rigid_17t_plus or hgv_average.Show 2 child attributesHide child attributes
2023 to 2026. Defaults to the latest published set.WTW well-to-wake (default) or TTW tank-to-wake only.Response
200: the calculated result. For errors see Errors.
null.Show 7 child attributesHide child attributes
0 in this version: time in port is not included, and a warning says so.0 in this version: terminal handling is not included, and a warning says so.Show 8 child attributesHide child attributes
provided: the distance you sent. calculated: the shortest sea route, worked out by Switch because the sea leg had no distance_km. A warning names the leg.value, unit, description and published source with version.default: a published factor was used.0 in this version). They add up to co2e_kg.co2e_kg.WTW or TTW, as applied.ISO 14083, distance-based.default: every leg used published factors.For live operations, push each port-call timestamp to Switch the moment it happens instead of sending a finished call. Switch keeps a running result for the port call and tells your system when it changes, by webhook.
Authorizations
AuthorizationBearerrequiredYour API key.Path parameters
timestampID in the body.Body
A standard port-call Timestamp, plus the port call ID, port, vessel and the service and event codes that identify it.
BERTH, ANCHORAGE or CARGO_OPERATIONS. Other upper-case standard service types are accepted and stored but not used in the calculation.ARRI, DEPA, STRT or CMPL.EST, REQ, PLN or ACT.Response
202 Accepted: the timestamp was received and the running result will update.
running, or finalized once the actual berth departure (BERTH DEPA ACT) has been accepted.How timestamps are handled
- The first timestamp for a new
portCallIDstarts the port call. Later timestamps must have the same port and vessel. - Sending the same
timestampIDagain with the same content changes nothing. Sending it with different content replaces that timestamp. AtimestampIDalready used for another port call is rejected with422. - When several timestamps describe the same moment, the one with the latest
dateTimeis used. A planned berth arrival is used before an estimated one. - An actual berth arrival earlier than planned is accepted. Waiting time is then
0. - The actual berth departure (
BERTH DEPA ACT) finalizes the call. It is accepted only when the call is complete, otherwise the API answers422 missing_timestampand names the timestamp still needed, for exampleMissing timestamp: CARGO_OPERATIONS CMPL ACT. - After the call is finalized, resending one of its timestamps unchanged returns
finalized. Any other timestamp for the call answers422withThis port call is finalized. - Real-time results use the vessel profile Switch set on your account at onboarding: the auxiliary burn rate, the fuel and the idle baseline.
Initial release
The first version of the Switch Freight Emissions API.
Endpoints
- POST
/v1/emissions/shipment: emissions (CO₂e) for a container shipment across sea, road and rail legs. - POST
/v1/emissions/port-call: CO₂ for a whole port call, necessary and avoidable, in standard or simple format. - GET
/v1/emissions/{id}: a stored result, exactly as calculated. - PUT
/v1/port-call/timestamps/{timestampID}: push port-call timestamps as they happen.
Webhook events
emission.updatedandemission.finalized, signed withX-Switch-Signature.
Included
- Well-to-wake results by default, with the tank-to-wake and well-to-tank parts returned separately.
- Factor sets from 2023 to 2026, with the factor, source and version named on every leg.
- Factors by vessel size for sea legs, by vehicle type for road legs, and refrigerated road factors for reefers.
- Warnings on every result that list what was missing or assumed.
- Sea distances calculated by Switch when
distance_kmis left out on a sea leg.
Each leg is calculated with a published factor for its mode, and for its vehicle or vessel size when you send one. The result names the factor, its source and version, and lists in warnings[] anything that was missing or assumed.
How the result says what was used
| Field | Values |
|---|---|
legs[].factor | The factor applied to the leg: value, unit, description and published source with version. |
legs[].data_type | default: a published factor was used. |
data_quality | default: every leg used published factors. |
method | ISO 14083, distance-based. |
legs[].distance_source | provided: the distance you sent. calculated: the shortest sea route, worked out by Switch because the sea leg had no distance_km. |
Warnings
warnings[] lists data that was missing or assumed, so nothing is left out silently. Examples from real responses:
No waiting time sent for the sea leg; time in port is not included.No hubs sent; terminal handling is not included.Scope TTW requested; ISO 14083 reporting requires WTW.No refrigerated factor for sea legs; the average factor was used for leg 1.
A result without a vessel size uses the fleet average factor, and a sea leg without a distance uses the calculated sea route. The warnings name the leg in both cases.
See Reefers and what a result covers for what the time in port and terminal handling warnings mean.
Show warnings to your users next to the number. They explain exactly what the figure includes.
Error shape
{
"error": {
"code": "invalid_unlocode",
"message": "XXXXX is not a recognised UN/LOCODE.",
"field": "legs[0].origin.unlocode"
}
}
Caught errors never calculate. Read error.code in your code and show error.message to people. error.field names the field that caused the error, so you can point to it in a form.
Status codes
| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | The body is not valid JSON, is larger than 256 KB, has a field the endpoint does not know, or has a field with the wrong type. |
| 401 | unauthorized | The API key is missing, revoked or invalid. Check the Authorization header. |
| 403 | forbidden | Your plan does not include this endpoint or volume. Contact sales to change your plan. |
| 404 | not_found | No result exists with that ID. |
| 422 | missing_field | A required field is missing. field names it. |
| 422 | invalid_value | A value is outside the allowed list or range, for example an unknown mode or a factor_year outside 2023 to 2026. |
| 422 | invalid_unlocode | A location code is not recognised. |
| 422 | missing_timestamp | A required timestamp is missing. The error names the service, event and classifier codes expected. |
| 422 | timestamp_order | Port-call timestamps are out of order, for example berth departure before cargo completion. |
| 422 | invalid_fuel_type | vessel_profile.fuel_type is not HFO, VLSFO, MGO or LNG. |
| 422 | missing_weight | cargo.weight_tonnes is missing, zero or negative. |
| 429 | rate_limited | Too many requests. Wait for the time in the Retry-After header. |
| 500 | server_error | Something failed on our side. Retry with backoff and contact support if it continues. |
Two answers do not use the error shape above. A path that does not exist answers 404 with {"detail": "Not Found"}. A method an endpoint does not support, for example DELETE, answers 405 with {"detail": "Method Not Allowed"}. Check the method and path against the endpoint list.
The body only has to be valid JSON. Send Content-Type: application/json as good practice.
Every response carries an X-Request-Id header. Quote it when you contact support@switchclimatetech.com.
When it is sent
Switch sends emission.finalized when the actual departure from berth (BERTH DEPA ACT) arrives for a port call you are pushing in real time. From that moment the result is locked with its factor version.
Payload
The complete port-call result, with the event fields added.
emission.finalizedfinalizednull: the call is complete.{
"event": "emission.finalized",
"event_id": "evt_4Wn7pR2cJ8",
"created_at": "2026-11-23T20:00:03Z",
"id": "emi_3Pc8vR2tY6",
"port_call_id": "398d26ef-2f5f-4c5a-9bd0-6c67c7123bb5",
"status": "finalized",
"next_expected": null,
"validation": {
"status": "valid",
"input_format": "standard",
"waiting_method": "berth_arrival_actual_minus_planned",
"warnings": []
},
"time": {
"waiting_hours": 0.5,
"berthing_hours": 1.5,
"cargo_ops_hours": 5.0,
"idle_hours": 2.0,
"total_hours": 9.0
},
"emissions": {
"total": { "hours": 9.0, "fuel_t": 2.25, "co2_t": 7.01 },
"necessary": { "hours": 6.5, "fuel_t": 1.625, "co2_t": 5.06 },
"avoidable": { "hours": 2.5, "fuel_t": 0.625, "co2_t": 1.95, "share_of_total": 0.28 }
},
"emission_factor": {
"value": 3.114,
"unit": "t CO2/t fuel",
"source": "IMO EEDI guidelines, MEPC.364(79), HFO"
},
"savings_vs_baseline": {
"baseline_idle_hours": 1.0,
"excess_idle_hours": 1.0,
"fuel_t": 0.25,
"co2_t": 0.78,
"share_of_avoidable": 0.4,
"share_of_total": 0.11
},
"insights": [
"28% of this call's CO2 (1.95 t of 7.01 t) was avoidable.",
"Vessel reached the berth 0.5 h after the planned arrival.",
"Vessel stayed 2.0 h at berth after cargo completion, 1.0 h over the baseline. Cutting idle time to the baseline saves 0.78 t CO2."
],
"calculated_at": "2026-11-23T20:00:02Z"
}
What to do
- Verify the signature
Check
X-Switch-Signatureas described in Signature verification. - De-duplicate on
event_idA failed delivery is retried up to 6 times, from 1 minute to 24 hours apart, so the same event can arrive more than once.
- Store the final figures
The payload holds the complete result.
GET /v1/emissions/{id}returns the same result at any time.
Until emission.finalized, Retrieve a result returns the latest running result. After it, Retrieve returns the locked result.
Sent when a new timestamp changes the time split or CO₂ of a running port-call result, for example when cargo operations complete and the idle clock starts.
Headers
Payload
emission.updatedrunningwaiting_hours, berthing_hours, cargo_ops_hours, idle_hours.total.co2_t and avoidable.co2_t, in metric tonnes.BERTH DEPA ACT.A failed delivery is retried up to 6 times, from 1 minute to 24 hours apart, so the same event can arrive more than once or out of order. De-duplicate on event_id. A timestamp that changes neither the time split nor the CO₂ sends no event.
| Used for | Source |
|---|---|
| Sea, container ship | DEFRA |
| Road, truck | DEFRA |
| Rail freight, average | DEFRA |
| Well-to-tank | DEFRA |
| Port call, marine fuel | IMO |
Factor years
Set options.factor_year to apply a factor set from 2023 to 2026. When you leave it out, the latest published set is used. Each result names the exact source and version, for example DEFRA GHG Conversion Factors 2026 v1, or IMO EEDI guidelines, MEPC.364(79), HFO for a port call.
DEFRA factors are the UK Government greenhouse-gas conversion factors, published every year. The IMO factors are the carbon factors per tonne of marine fuel from the IMO EEDI guidelines.
See it work
One container, Shanghai to Düsseldorf
A 40 ft container with 18.5 t of cargo, sent as one API call. Switch matches a factor to each leg and returns the footprint.
- 01Your platform sends the route
- 02Switch matches factors
- 03Sea leg calculated
- 04Road leg calculated
- 05Emissions returned
- km
- 0
- kg CO₂e
- 0.0
- km
- 0
- kg CO₂e
- 0.0
Ready.
Send the request
Send one leg per transport segment. Here the container sails from Shanghai (CNSHA) to Rotterdam (NLRTM) on a 14,000 TEU vessel, then travels by road to Düsseldorf (DEDUS).
curl -X POST "$SWITCH_API_BASE/v1/emissions/shipment" \ -H "Authorization: Bearer $SWITCH_API_KEY" \ -H "Content-Type: application/json" \ -d @shipment.json
import os, requests
BASE = os.environ["SWITCH_API_BASE"]
HEADERS = {"Authorization": f"Bearer {os.environ['SWITCH_API_KEY']}"}
shipment = {
"reference": "MSCU1234567",
"cargo": {"containers": 1, "teu_per_container": 2,
"reefer": False, "weight_tonnes": 18.5},
"legs": [
{"mode": "sea", "origin": {"unlocode": "CNSHA"},
"destination": {"unlocode": "NLRTM"}, "distance_km": 19630,
"vessel": {"size_teu": 14000},
"departure": "2026-10-01T08:00:00Z", "arrival": "2026-11-02T14:00:00Z"},
{"mode": "road", "origin": {"unlocode": "NLRTM"},
"destination": {"unlocode": "DEDUS"}, "distance_km": 230},
],
"options": {"factor_year": 2026, "scope": "TTW"},
}
resp = requests.post(f"{BASE}/v1/emissions/shipment", json=shipment, headers=HEADERS)
result = resp.json()
print(result["total"]["co2e_kg"]) # 4930.9
const BASE = process.env.SWITCH_API_BASE;
const KEY = process.env.SWITCH_API_KEY;
const shipment = {
reference: "MSCU1234567",
cargo: { containers: 1, teu_per_container: 2, reefer: false, weight_tonnes: 18.5 },
legs: [
{ mode: "sea", origin: { unlocode: "CNSHA" }, destination: { unlocode: "NLRTM" },
distance_km: 19630, vessel: { size_teu: 14000 },
departure: "2026-10-01T08:00:00Z", arrival: "2026-11-02T14:00:00Z" },
{ mode: "road", origin: { unlocode: "NLRTM" }, destination: { unlocode: "DEDUS" },
distance_km: 230 },
],
options: { factor_year: 2026, scope: "TTW" },
};
const resp = await fetch(`${BASE}/v1/emissions/shipment`, {
method: "POST",
headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
body: JSON.stringify(shipment),
});
const result = await resp.json();
console.log(result.total.co2e_kg); // 4930.9
{
"reference": "MSCU1234567",
"cargo": {
"containers": 1,
"teu_per_container": 2,
"reefer": false,
"weight_tonnes": 18.5
},
"legs": [
{
"mode": "sea",
"origin": { "unlocode": "CNSHA" },
"destination": { "unlocode": "NLRTM" },
"distance_km": 19630,
"vessel": { "size_teu": 14000 },
"departure": "2026-10-01T08:00:00Z",
"arrival": "2026-11-02T14:00:00Z"
},
{
"mode": "road",
"origin": { "unlocode": "NLRTM" },
"destination": { "unlocode": "DEDUS" },
"distance_km": 230
}
],
"options": { "factor_year": 2026, "scope": "TTW" }
}
This example asks for tank-to-wake ("scope": "TTW") so the numbers match the animation above. Leave options.scope out to get well-to-wake, the default. ISO 14083 reporting requires well-to-wake results. See Well-to-wake vs tank-to-wake.
Read the result
{
"id": "emi_7Hq2kZ4mN1",
"reference": "MSCU1234567",
"total": {
"co2e_kg": 4930.9,
"co2e_kg_per_teu": 2465.5,
"sailing_co2e_kg": 4930.9,
"waiting_co2e_kg": 0.0,
"hubs_co2e_kg": 0.0,
"distance_km": 19860
},
"legs": [
{
"mode": "sea",
"origin": "CNSHA",
"destination": "NLRTM",
"distance_km": 19630,
"distance_source": "provided",
"factor": {
"value": 0.01266,
"unit": "kg CO2e/t-km",
"description": "Container ship, 8000+ TEU",
"source": "DEFRA GHG Conversion Factors 2026 v1"
},
"data_type": "default",
"sailing_co2e_kg": 4597.5,
"waiting_co2e_kg": 0.0,
"co2e_kg": 4597.5
},
{
"mode": "road",
"origin": "NLRTM",
"destination": "DEDUS",
"distance_km": 230,
"distance_source": "provided",
"factor": {
"value": 0.07835,
"unit": "kg CO2e/t-km",
"description": "HGV, articulated >33 t, average laden, diesel",
"source": "DEFRA GHG Conversion Factors 2026 v1"
},
"data_type": "default",
"sailing_co2e_kg": 333.4,
"waiting_co2e_kg": 0.0,
"co2e_kg": 333.4
}
],
"hubs": [],
"scope": "TTW",
"method": "ISO 14083, distance-based",
"data_quality": "default",
"warnings": [
"No waiting time sent for the sea leg; time in port is not included.",
"No hubs sent; terminal handling is not included.",
"Scope TTW requested; ISO 14083 reporting requires WTW."
],
"calculated_at": "2026-11-02T14:05:12Z"
}
The headline number is total.co2e_kg: 4,930.9 kg CO₂e for the whole journey, or 2,465.5 kg per TEU (total.co2e_kg_per_teu). Every leg names the factor it used, so each number can be checked.
| Leg | Factor | Source | CO₂e |
|---|---|---|---|
| Sea · CNSHA → NLRTM | 0.01266 kg CO₂e/t-kmContainer ship, 8000+ TEU | DEFRA GHG Conversion Factors 2026 v1 | 4,597.5 kg |
| Road · NLRTM → DEDUS | 0.07835 kg CO₂e/t-kmHGV, articulated >33 t, average laden, diesel | DEFRA GHG Conversion Factors 2026 v1 | 333.4 kg |
| Total | 4,930.9 kg |
Warnings tell you what was left out
The response lists data that was missing or assumed, so nothing is left out silently. In this example:
- No waiting time sent for the sea leg. The result covers the movement of each leg. Time the vessel spends in port is not included.
- No hubs sent. Terminal handling between legs is not included.
- Scope TTW requested. ISO 14083 reporting requires WTW.
See Reefers and what a result covers.
Leave the sea distance out
distance_km is optional for sea legs. When you leave it out, Switch calculates the shortest sea route between the two ports, marks the leg distance_source: calculated and adds a warning that names the leg. Road and rail legs always need a distance.
{
"mode": "sea",
"origin": { "unlocode": "CNSHA" },
"destination": { "unlocode": "NLRTM" },
"vessel": { "size_teu": 14000 }
}Next
No term matches. Try a shorter word.
Shipping and ports
- TEU
- Twenty-foot Equivalent Unit, the standard measure of container capacity. A 20 ft container is 1 TEU, a 40 ft container is 2 TEU.
- UN/LOCODE
- United Nations five-character code for ports and places, for example
CNSHA(Shanghai) orNLRTM(Rotterdam). - IMO number
- Permanent seven-digit identifier of a ship, assigned under the International Maritime Organization scheme.
- Port call
- A ship's visit to a port, from arrival to departure.
- Berth
- The place at a quay where a ship moors to load and unload.
- Anchorage
- A sea area outside the port where ships wait at anchor until a berth is free.
- Hub
- A terminal or warehouse where a container is handled between transport legs. Terminal handling at hubs is not included in shipment results.
- Transshipment
- Moving a container from one vessel to another at an intermediate port.
- Reefer
- A refrigerated container.
- Nautical mile (nm)
- 1.852 km. Sea distances are usually given in nautical miles.
- 3PL
- Third-party logistics provider that manages transport and warehousing for shippers.
Emissions and standards
- CO₂e
- Carbon dioxide equivalent: CO₂, methane and nitrous oxide combined by their warming effect.
- Emission factor
- The emissions per unit of activity, for example kg CO₂e per tonne-km.
- Tonne-km (t-km)
- One tonne of cargo moved one kilometre. Freight factors are expressed per tonne-km.
- TTW · WTT · WTW
- Tank-to-wake (burning the fuel), well-to-tank (producing and delivering the fuel) and well-to-wake (both together).
- Scope 1 · Scope 3
- GHG Protocol categories. Scope 1 is direct emissions from sources a company operates. Scope 3 includes transport it buys from others.
- GHG Protocol
- The most widely used corporate greenhouse-gas accounting standard.
- ISO 14083
- International standard for quantifying greenhouse-gas emissions from transport chains.
- GLEC Framework
- Smart Freight Centre's method for logistics emissions, aligned with ISO 14083.
- DEFRA factors
- UK Government greenhouse-gas conversion factors, published every year.
- CSRD
- EU Corporate Sustainability Reporting Directive. It requires in-scope companies to report Scope 1, 2 and, where material, Scope 3 emissions under ESRS E1.
Fuels and vehicles
- HFO · VLSFO · MGO · LNG
- Heavy fuel oil, very low sulphur fuel oil, marine gas oil and liquefied natural gas.
- Auxiliary engine
- The ship's generator engines. They power the ship in port when the main engine is off.
- HGV · artic
- Heavy goods vehicle, a truck over 3.5 t. An artic is an articulated truck: tractor unit plus trailer.
Technical
- API key
- The secret that identifies your account, sent as a Bearer token on every request.
- Webhook
- A message Switch sends to your system when a result changes, instead of you asking for it.
- ISO 8601
- The standard date-time format, for example
2026-11-23T18:00:00Z.
Switch Freight Emissions API
Emissions for every container, leg and port call.
Send the shipment and port-call data you already track. Get back emissions in CO₂e with the factor, source and version behind every number. One API, built on published standards, ready to sit inside your product.
POST /v1/emissions/shipmentEmissions (CO₂e) for a container across sea, road and rail legs, per leg and per TEU.
Port callsPOST /v1/emissions/port-callCO₂ for a whole port call, split into necessary and avoidable time, from timestamps in industry-standard format.
Real timePUT /v1/port-call/timestamps/{id}Stream port-call events as they happen. Results update live and arrive by webhook.
See it work
One container, Shanghai to Düsseldorf
A 40 ft container with 18.5 t of cargo, sent as one API call. Switch matches a factor to each leg and returns the footprint.
- 01Your platform sends the route
- 02Switch matches factors
- 03Sea leg calculated
- 04Road leg calculated
- 05Emissions returned
- km
- 0
- kg CO₂e
- 0.0
- km
- 0
- kg CO₂e
- 0.0
Ready.
Explore the docs
Who uses it
Add emissions to every shipment you track
Subscribe to the Switch Freight Emissions API. Credentials are issued once your subscription is allotted.
Base URL
Your API base URL is issued with your subscription. The examples read it from the SWITCH_API_BASE environment variable.
export SWITCH_API_BASE="https://<your-base-url>" # issued with your subscription export SWITCH_API_KEY="sk_live_..." # your API key
Authentication
Every request is authenticated with your API key, sent as a Bearer token in the Authorization header. There is no separate login or token call.
Authorization: Bearer $SWITCH_API_KEYrequiredon every requestYour Client ID (cli_...) is the public identifier of your account. It is not a secret. Your API key (sk_live_...) is secret and linked to your subscription plan. See Start here.
Requests and responses
- Send JSON bodies with
Content-Type: application/json, up to 256 KB. Responses are JSON. - Fields the endpoint does not know are rejected with
400 bad_request, and the error names the field. Check the spelling against the reference. - The version is in the path: every endpoint starts with
/v1. - Optional fields may be left out or sent as
null, which is treated as not sent. - Every response carries an
X-Request-Idheader. Authenticated API calls also carry rate limit headers. See Rate limits. - Errors share one shape with a code, a message and the field that caused them. See Errors.
Conventions
| Topic | Convention |
|---|---|
| Places | UN/LOCODE, for example CNSHA, NLRTM, SGSIN. |
| Times | ISO 8601. Results report calculated_at in UTC. |
| Units | Distance in km, cargo weight in metric tonnes, shipment emissions in kg CO₂e, port-call emissions and fuel in metric tonnes, time in hours. |
| Rounding | Each figure is rounded on its own, so parts can differ from the total by 0.01. |
| IDs | Results start with emi_, webhook events with evt_. |
Endpoints
| Method | Path | What it does |
|---|---|---|
| POST | /v1/emissions/shipment | Emissions (CO₂e) for a container shipment, per leg and per TEU. |
| POST | /v1/emissions/port-call | CO₂ for a whole port call, necessary and avoidable. |
| GET | /v1/emissions/{id} | A stored result, exactly as it was calculated. |
| PUT | /v1/port-call/timestamps/{timestampID} | Push a port-call timestamp as it happens. |
Shipments: a transport chain of legs
Shipment results are calculated in line with ISO 14083 and the GLEC Framework: a transport chain of legs, reported well-to-wake by default and compatible with the GHG Protocol. ISO 14083 reporting requires well-to-wake results. A tank-to-wake result is for internal analysis. CO₂e uses the 100-year global warming potentials applied in each cited factor set.
Published factors
Each leg uses a published factor for its mode, and for its vehicle or vessel size when you send one. Time in port and terminal handling are not included, and the warnings in each result say so. See Data quality and warnings.
Port calls
Port-call results are estimates of the CO₂ for the whole call, split into necessary and avoidable time. See How port-call emissions are split.
Traceable and reproducible
Factors come from published sources, and every result names the factor, its source and version year. Stored results keep the factor version they were calculated with, so they can be reproduced after factors are updated.
Scopes
For shippers and forwarders, all results are Scope 3 (Category 4, upstream transportation, or Category 9, downstream). For the operator of the vessel or truck, tank-to-wake fuel emissions are Scope 1 and well-to-tank is Scope 3 Category 3. See Well-to-wake vs tank-to-wake.
Transport modes
| Mode | Value | Factor |
|---|---|---|
| Sea, container ship | sea | By vessel size band, or the fleet average when no size is sent. |
| Road, truck | road | By vehicle, diesel. Refrigerated when cargo.reefer is true. |
| Rail freight | rail | Freight train, average. |
Vessel size
Send vessel.size_teu and Switch picks the matching size band. The result names the band in legs[].factor.description, for example Container ship, 8000+ TEU. Without a size, the fleet average factor is used and a warning says so.
Road vehicles
| Value | Vehicle |
|---|---|
artic_33t_plus | Articulated truck over 33 t. The default. |
artic_3.5_33t | Articulated truck from 3.5 t to 33 t. |
rigid_17t_plus | Rigid truck over 17 t. |
hgv_average | Average heavy goods vehicle. |
Port calls
| Fuel | Value | Factor applied |
|---|---|---|
| Heavy fuel oil | HFO (default) | HFO |
| Very low sulphur fuel oil | VLSFO | HFO. The result names the HFO factor as its source. |
| Marine gas oil | MGO | MGO |
| Liquefied natural gas | LNG | LNG |
Set the fuel in vessel_profile.fuel_type. Auxiliary engine fuel use is vessel_profile.aux_burn_rate_tph. When you leave it out, the vessel profile Switch set on your account at onboarding is used.
Tracking platforms, forwarders, carriers and ports hold the data that decides a shipment's footprint: the ports it called at, the vessel that carried it, and how long it sat waiting. The Switch Freight Emissions API turns that data into greenhouse-gas figures you can show customers and put in a report.
You keep collecting the data. Switch does the calculation: choosing the right factor, converting units, applying the standard and returning the result with its source.
About CO₂e. Results are greenhouse-gas emissions expressed in CO₂e, carbon dioxide equivalent: CO₂, methane and nitrous oxide combined by their warming effect. This is the unit used by the GHG Protocol, ISO 14083 and EU sustainability reporting under CSRD. Port-call results are fuel-combustion CO₂ and are labelled CO₂.
What you can calculate
Why teams use it
- No emissions team needed. Factor selection, versioning and unit handling are done for you.
- Every number can be traced. Each result names the factor, its published source and version year.
- Built on open standards. Port-call input follows the open industry standard for port-call data, so existing feeds plug in as they are.
- Only what the calculation needs. You send ports, distances, weights and timestamps. No commercial or customer data is required.
New to shipping or emissions terms such as TEU, UN/LOCODE or tonne-km? See the Glossary.
Plans scale with monthly API volume, service level and deployment needs, from a single integration to enterprise and platform partners who offer Switch results to their own customers.
How to get access
- Send the request form
Tell us your company, the data you hold and the volume you expect.
- Agree your plan
We agree the plan and service level that fit your volume.
- Get your credentials
Once your subscription is allotted, you receive your Client ID, API key, API base URL and an onboarding call.
Request access
Already a customer? Write to support@switchclimatetech.com for technical help.
A container vessel calls at Singapore. Five timestamps describe the call.
- 1Planned berth arrival11:00
- 2Berth arrival11:30
- 3Cargo ops start13:00
- 4Cargo ops end18:00
- 5Berth departure20:00
Total CO₂
0.00t
Whole call · 9.0 h
Avoidable CO₂
0.00t
0% of the call
Avoidable time
0.0h
0.00 t fuel
Saving at 1 h idle
0.78t CO₂
11% of the call
The four phases
| Phase | Counts as | Example |
|---|---|---|
| Waiting for berth | Avoidable | 0.5 h |
| Berthing | Necessary | 1.5 h |
| Cargo operations | Necessary | 5.0 h |
| Idle after cargo | Avoidable | 2.0 h |
Every result names the factor, source and version used. Avoidable counts all idle time after cargo completion. baseline.idle_hours only changes savings_vs_baseline.
Which timestamps to send is listed in Standard port-call data. Anchorage start and completion are optional and improve the waiting figure. An actual berth arrival earlier than planned is accepted, and waiting time is then 0.
Estimate. Port-call results are estimates of tank-to-wake CO₂ for the vessel while in port. They use the auxiliary burn rate you send, or the vessel profile Switch set on your account at onboarding. The full scope and assumptions are shared at onboarding.
A container vessel calls at Singapore. Five timestamps describe the call.
- 1Planned berth arrival11:00
- 2Berth arrival11:30
- 3Cargo ops start13:00
- 4Cargo ops end18:00
- 5Berth departure20:00
Total CO₂
0.00t
Whole call · 9.0 h
Avoidable CO₂
0.00t
0% of the call
Avoidable time
0.0h
0.00 t fuel
Saving at 1 h idle
0.78t CO₂
11% of the call
Switch separates the necessary part of a port call (berthing and cargo operations) from the avoidable part (waiting for a berth and idling after cargo operations). Input follows the open industry standard for port-call data, so timestamps from any compliant system can be sent as they are. The calculation, factors and results are Switch's own.
Send the timestamps
Send the call in the standard format, or in the simple format if your system does not use the standard. Both describe the same five moments.
{
"portCall": {
"portCallID": "398d26ef-2f5f-4c5a-9bd0-6c67c7123bb5",
"UNLocationCode": "SGSIN",
"vessel": { "vesselIMONumber": "9321483" }
},
"timestamps": [
{ "portCallServiceTypeCode": "BERTH", "portCallServiceEventTypeCode": "ARRI",
"classifierCode": "PLN", "dateTime": "2026-11-23T11:00:00Z" },
{ "portCallServiceTypeCode": "BERTH", "portCallServiceEventTypeCode": "ARRI",
"classifierCode": "ACT", "dateTime": "2026-11-23T11:30:00Z" },
{ "portCallServiceTypeCode": "CARGO_OPERATIONS", "portCallServiceEventTypeCode": "STRT",
"classifierCode": "ACT", "dateTime": "2026-11-23T13:00:00Z" },
{ "portCallServiceTypeCode": "CARGO_OPERATIONS", "portCallServiceEventTypeCode": "CMPL",
"classifierCode": "ACT", "dateTime": "2026-11-23T18:00:00Z" },
{ "portCallServiceTypeCode": "BERTH", "portCallServiceEventTypeCode": "DEPA",
"classifierCode": "ACT", "dateTime": "2026-11-23T20:00:00Z" }
],
"vessel_profile": { "aux_burn_rate_tph": 0.25, "fuel_type": "HFO" },
"baseline": { "idle_hours": 1 }
}
{
"port_call_id": "398d26ef-2f5f-4c5a-9bd0-6c67c7123bb5",
"unlocode": "SGSIN",
"vessel_imo": "9321483",
"times": {
"berth_arrival_planned": "2026-11-23T11:00:00Z",
"berth_arrival_actual": "2026-11-23T11:30:00Z",
"cargo_ops_start": "2026-11-23T13:00:00Z",
"cargo_ops_end": "2026-11-23T18:00:00Z",
"berth_departure_actual": "2026-11-23T20:00:00Z"
},
"vessel_profile": { "aux_burn_rate_tph": 0.25, "fuel_type": "HFO" },
"baseline": { "idle_hours": 1 }
}
curl -X POST "$SWITCH_API_BASE/v1/emissions/port-call" \ -H "Authorization: Bearer $SWITCH_API_KEY" \ -H "Content-Type: application/json" \ -d @port-call.json
import os, json, requests
BASE = os.environ["SWITCH_API_BASE"]
HEADERS = {"Authorization": f"Bearer {os.environ['SWITCH_API_KEY']}"}
port_call = json.load(open("port-call.json")) # either format above
resp = requests.post(f"{BASE}/v1/emissions/port-call", json=port_call, headers=HEADERS)
result = resp.json()
print(result["emissions"]["avoidable"]["co2_t"]) # 1.95
import { readFileSync } from "node:fs";
const BASE = process.env.SWITCH_API_BASE;
const KEY = process.env.SWITCH_API_KEY;
const portCall = JSON.parse(readFileSync("port-call.json", "utf8")); // either format
const resp = await fetch(`${BASE}/v1/emissions/port-call`, {
method: "POST",
headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
body: JSON.stringify(portCall),
});
const result = await resp.json();
console.log(result.emissions.avoidable.co2_t); // 1.95
Required timestamps: berth arrival planned (or estimated), berth arrival actual, cargo operations start and completion, and berth departure actual. Anchorage start and completion are optional and improve the waiting figure.
Read the result
{
"id": "emi_3Pc8vR2tY6",
"port_call_id": "398d26ef-2f5f-4c5a-9bd0-6c67c7123bb5",
"validation": {
"status": "valid",
"input_format": "standard",
"waiting_method": "berth_arrival_actual_minus_planned",
"warnings": []
},
"time": {
"waiting_hours": 0.5,
"berthing_hours": 1.5,
"cargo_ops_hours": 5.0,
"idle_hours": 2.0,
"total_hours": 9.0
},
"emissions": {
"total": { "hours": 9.0, "fuel_t": 2.25, "co2_t": 7.01 },
"necessary": { "hours": 6.5, "fuel_t": 1.625, "co2_t": 5.06 },
"avoidable": { "hours": 2.5, "fuel_t": 0.625, "co2_t": 1.95,
"share_of_total": 0.28 }
},
"emission_factor": { "value": 3.114, "unit": "t CO2/t fuel", "source": "IMO EEDI guidelines, MEPC.364(79), HFO" },
"savings_vs_baseline": {
"baseline_idle_hours": 1.0,
"excess_idle_hours": 1.0,
"fuel_t": 0.25,
"co2_t": 0.78,
"share_of_avoidable": 0.4,
"share_of_total": 0.11
},
"insights": [
"28% of this call's CO2 (1.95 t of 7.01 t) was avoidable.",
"Vessel reached the berth 0.5 h after the planned arrival.",
"Vessel stayed 2.0 h at berth after cargo completion, 1.0 h over the baseline. Cutting idle time to the baseline saves 0.78 t CO2."
],
"calculated_at": "2026-11-23T20:05:00Z"
}
| Figure | Value | Field |
|---|---|---|
| Total CO₂ for the call | 7.01 t over 9.0 h | emissions.total.co2_t |
| Necessary: berthing and cargo operations | 5.06 t over 6.5 h | emissions.necessary.co2_t |
| Avoidable: waiting and idle time | 1.95 t over 2.5 h, 28% of the call | emissions.avoidable |
| Saving if idle time is cut to the 1 h baseline | 0.78 t CO₂, 11% of the call | savings_vs_baseline.co2_t |
Each figure is rounded on its own, so parts can differ from the total by 0.01. The insights[] array says the same in plain language, ready to show to a user.
Estimate. Port-call results are estimates of tank-to-wake CO₂ for the vessel while in port. They use the auxiliary burn rate you send, or the vessel profile Switch set on your account at onboarding. The full scope and assumptions are shared at onboarding.
Next
Rate limit headers
Limits depend on your plan. Every authenticated API call returns headers showing where you stand. X-RateLimit-Reset is the Unix time, in seconds, when the window resets. The values below are examples only.
X-RateLimit-Limit: 600 X-RateLimit-Remaining: 598 X-RateLimit-Reset: 1793174400
| Header | Meaning |
|---|---|
X-RateLimit-Limit | Requests allowed in the current window on your plan. |
X-RateLimit-Remaining | Requests left in the current window. |
X-RateLimit-Reset | Unix time, in seconds, when the window resets. |
Retry-After | Sent with 429 rate_limited: how long to wait before trying again. |
When you hit the limit
A 429 response with the code rate_limited means too many requests. Wait for the time in the Retry-After header, then send the request again. To raise your limits, change your plan.
Request IDs
Every response also carries an X-Request-Id header. Log it with your own request, and quote it when you contact support.
- Push timestamps as they happen
PUTeach timestamp to/v1/port-call/timestamps/{timestampID}. Switch answers202 Acceptedwith the running result ID. - Receive
emission.updatedSent when a new timestamp changes the time split or CO₂.
- Receive
emission.finalizedSent when the actual departure from berth arrives. The result is locked with its factor version.
1. Push timestamps as they happen
The body is a standard port-call Timestamp, plus the port call ID, port, vessel and the service and event codes that identify it. If you already send these timestamps to other parties, point the same feed at Switch.
{
"timestampID": "0342254a-5927-4856-b9c9-aa12e7c00563",
"portCallID": "398d26ef-2f5f-4c5a-9bd0-6c67c7123bb5",
"UNLocationCode": "SGSIN",
"vesselIMONumber": "9321483",
"portCallServiceTypeCode": "CARGO_OPERATIONS",
"portCallServiceEventTypeCode": "CMPL",
"classifierCode": "ACT",
"dateTime": "2026-11-23T18:00:00Z"
}
{
"id": "emi_3Pc8vR2tY6",
"status": "running"
}
Sending the same timestampID again with different content replaces that timestamp. The actual berth departure is accepted once the call is complete, and then finalizes it. Real-time results use the vessel profile Switch set on your account at onboarding. See Push a timestamp for every rule.
2. Receive results by webhook
Register a webhook URL with your subscription. Switch sends an event when a running result changes and when it is final.
| Event | Sent when |
|---|---|
emission.updated | A new timestamp changes the time split or CO₂, for example when cargo operations complete and the idle clock starts. |
emission.finalized | The actual departure from berth arrives. The result is locked with its factor version and can be fetched with Retrieve a result. |
{
"event": "emission.updated",
"event_id": "evt_9Kd2mQ7xL4",
"created_at": "2026-11-23T18:00:04Z",
"id": "emi_3Pc8vR2tY6",
"port_call_id": "398d26ef-2f5f-4c5a-9bd0-6c67c7123bb5",
"status": "running",
"time": { "waiting_hours": 0.5, "berthing_hours": 1.5, "cargo_ops_hours": 5.0, "idle_hours": 0.0 },
"emissions": {
"total": { "co2_t": 5.45 },
"avoidable": { "co2_t": 0.39 }
},
"next_expected": "BERTH DEPA ACT"
}
Every delivery is signed with X-Switch-Signature. Verify it before you trust the payload. See Signature verification.
Capture as you go. Many port-call data sources stop returning a call after it closes. Pushing timestamps during the call means nothing is lost when the call closes.
A shipment result covers the movement of the legs you send. This page explains how refrigerated containers are handled and what the result leaves out, so you can show the figure with the right context.
Refrigerated containers
Set cargo.reefer to true for refrigerated containers.
| Leg | Factor used |
|---|---|
| Road | The refrigerated factor for the vehicle, for example HGV, articulated >33 t, average laden, refrigerated, diesel. |
| Sea and rail | The average factor for the mode, with a warning that names the leg, for example No refrigerated factor for sea legs; the average factor was used for leg 1. |
{
"reference": "MSCU1234567",
"cargo": { "containers": 1, "teu_per_container": 2, "reefer": true, "weight_tonnes": 18.5 },
"legs": [
{
"mode": "sea",
"origin": { "unlocode": "CNSHA" },
"destination": { "unlocode": "NLRTM" },
"vessel": { "size_teu": 14000 }
},
{
"mode": "road",
"origin": { "unlocode": "NLRTM" },
"destination": { "unlocode": "DEDUS" },
"distance_km": 230
}
]
}What a shipment result covers
| Part of the journey | In the result |
|---|---|
| Movement on each leg you send | Included, per leg, in legs[] and in total. |
| Time the vessel spends in port | Not included. waiting_co2e_kg is 0 and a warning says so on every result with a sea leg. |
| Terminal handling between legs | Not included. hubs is an empty list, total.hubs_co2e_kg is 0 and a warning says so. |
To measure the CO₂ of a vessel's time in port, use port-call emissions. It covers the whole call for the vessel, separately from the shipment result.
Show the warnings to your users next to the number. They explain exactly what the figure includes.
The standard describes each moment of a port call with three codes: the service, the event and whether the time is estimated, requested, planned or actual. Switch accepts these timestamps directly. The table shows each moment, its simple-format field and the standard codes.
Timestamp mapping
| Moment | Simple format field | portCallServiceTypeCode | portCallServiceEventTypeCode | classifierCode |
|---|---|---|---|---|
| Estimated berth arrival | berth_arrival_estimated | BERTH | ARRI | EST |
| Planned berth arrival | berth_arrival_planned | BERTH | ARRI | PLN |
| Anchorage start | anchorage_start | ANCHORAGE | STRT | ACT |
| Anchorage end | anchorage_end | ANCHORAGE | CMPL | ACT |
| Actual berth arrival | berth_arrival_actual | BERTH | ARRI | ACT |
| Cargo operations start | cargo_ops_start | CARGO_OPERATIONS | STRT | ACT |
| Cargo operations complete | cargo_ops_end | CARGO_OPERATIONS | CMPL | ACT |
| Actual berth departure | berth_departure_actual | BERTH | DEPA | ACT |
Simple format fields
The simple format is for systems that do not use the standard. Its fields map one to one to standard timestamps.
| Simple format field | Type | Description |
|---|---|---|
port_call_id optional | string | Your port call reference. |
unlocode required | string | UN/LOCODE of the port. |
vessel_imo required | string | IMO number of the vessel. |
times.berth_arrival_planned required | ISO 8601 | Planned berth arrival. times.berth_arrival_estimated is accepted instead. |
times.berth_arrival_actual required | ISO 8601 | Actual berth arrival. |
times.cargo_ops_start, times.cargo_ops_end required | ISO 8601 | Actual start and completion of cargo operations. |
times.berth_departure_actual required | ISO 8601 | Actual berth departure. |
times.anchorage_start, times.anchorage_end optional | ISO 8601 | Actual time at anchor. Improves the waiting figure. |
vessel_profile, baseline optional | object | Same as in the standard format. |
Waiting time
Anchorage start and completion are optional and improve the waiting figure. If no planned arrival is sent, the estimate (EST) is used and a warning is returned.
Getting the data
The standard is free to use and its publisher does not host port-call data. The timestamps sit with the carriers, terminals and port authorities that exchange them. Send them to Switch from your own implementation, either per finished call with Port-call emissions or live with Real-time updates.
- Get your credentials
Subscribe through sales. Once your subscription is allotted, you receive your Client ID, your API key and your API base URL.
- Send your first shipment
Post the route legs and container details to
/v1/emissions/shipment. - Read the result
Read
total.co2e_kg, the split per leg and the factor, source and version behind each number. - Receive real-time port-call updates
Push each port-call timestamp as it happens and receive results by webhook.
Before you start
The calculation only needs operational data. No commercial or customer data is required.
- A subscription to the Switch Freight Emissions API. See Plans and access.
- UN/LOCODEs for each port and place, for example
CNSHA(Shanghai) orNLRTM(Rotterdam). - Distances for road and rail legs. For sea legs you can leave the distance out and Switch calculates the shortest sea route.
- Cargo weight in metric tonnes, and the number and size of the containers.
New to shipping or emissions terms such as TEU, UN/LOCODE or tonne-km? See the Glossary.
Get your credentials
Credentials are issued by Switch once your subscription is allotted. There is no separate login or token call.
| Credential | Format | What it is for |
|---|---|---|
| Client ID | cli_... | Public identifier of your account. Shown in logs and used when you contact support. Not a secret. |
| API key | sk_live_... | Your secret key. Sent on every request. Linked to your subscription plan. |
| API base URL | https://... | The address you send requests to. Issued with your subscription. |
Set your key
Store the API key as an environment variable on your server. The examples in these docs read the base URL and key from environment variables, so you can paste them as they are.
export SWITCH_API_BASE="https://<your-base-url>" # issued with your subscription export SWITCH_API_KEY="sk_live_..." # your API key
Send the Authorization header
Every request is authenticated with your API key, sent as a Bearer token in the Authorization header: Authorization: Bearer $SWITCH_API_KEY.
curl "$SWITCH_API_BASE/v1/emissions/emi_7Hq2kZ4mN1" \ -H "Authorization: Bearer $SWITCH_API_KEY"
import os, requests
BASE = os.environ["SWITCH_API_BASE"]
HEADERS = {"Authorization": f"Bearer {os.environ['SWITCH_API_KEY']}"}
resp = requests.get(f"{BASE}/v1/emissions/emi_7Hq2kZ4mN1", headers=HEADERS)
const BASE = process.env.SWITCH_API_BASE;
const HEADERS = { Authorization: `Bearer ${process.env.SWITCH_API_KEY}` };
const resp = await fetch(`${BASE}/v1/emissions/emi_7Hq2kZ4mN1`, { headers: HEADERS });
Keep your API key secret. Use it only in server-side code. To replace a key, contact support.
Continue the tutorial
Factors come from published sources, and every result names the factor, its source and version year. Stored results keep the factor version they were calculated with, so they can be reproduced after factors are updated.
The factor on every leg
Each leg in a shipment result carries a factor object: the value, its unit, a description and the published source with its version.
"factor": {
"value": 0.01266,
"unit": "kg CO2e/t-km",
"description": "Container ship, 8000+ TEU",
"source": "DEFRA GHG Conversion Factors 2026 v1"
}Port-call results carry the fuel factor in emission_factor, for example 3.114 t CO₂ per t of fuel from the IMO EEDI guidelines, MEPC.364(79), for HFO.
Choose the factor year
Set options.factor_year to apply a factor set from 2023 to 2026. When you leave it out, Switch uses the latest published set.
Results are stored as calculated
Retrieve a result returns a stored result exactly as it was calculated, including the factor versions used at that time. Use it for audit trails and for reports.
Call Switch again when your data moves from estimated to actual. Each call creates a new result with a new id, and earlier results are kept unchanged. Store the latest id against your shipment.
Where the factors come from
See Factor sources for the source used for each mode and fuel.
Visibility platforms already hold the ports, vessel and dates for each shipment. Map those fields to a Switch request, call the API when a shipment is created or updated, and show emissions next to every tracked container.
Field mapping
| Typical tracking field | Switch field | Note |
|---|---|---|
| Port of loading (UN/LOCODE) | legs[0].origin.unlocode | For example CNSHA. |
| Port of discharge (UN/LOCODE) | legs[0].destination.unlocode | For example NLRTM. |
| Vessel IMO number | legs[0].vessel.imo | Stored for audit. |
| Vessel capacity (TEU) | legs[0].vessel.size_teu | Selects the size-band factor. Fleet average if unknown. |
| Departure date (actual or estimated) | legs[0].departure | Send the estimate first, then the actual. |
| Arrival date (actual or estimated) | legs[0].arrival | Same as above. |
| Container length | cargo.teu_per_container | 20 ft → 1, 40 ft → 2, 45 ft → 2.25. |
| Container type | cargo.reefer | true for refrigerated containers. |
| Cargo weight | cargo.weight_tonnes | Sum across containers. From pounds, multiply by 0.000453592. |
| Sailed or routed distance | legs[].distance_km | From nautical miles, multiply by 1.852. Optional for sea legs: when left out, Switch calculates the shortest sea route. |
Convert tracking data into the units Switch expects.
Transshipment. Send one sea leg per vessel, using the stops from your container route data. Each leg gets its own factor. See Multi-leg and transshipment routes.
Example
import os, requests
TEU = {20: 1, 40: 2, 45: 2.25}
KEY = os.environ["SWITCH_API_KEY"]
def shipment_co2e(shipment):
"""shipment: one record from your tracking system."""
containers = shipment["containers"]
body = {
"reference": shipment["bill_of_lading"],
"cargo": {
"containers": len(containers),
"teu_per_container": TEU.get(containers[0]["length_ft"], 2),
"reefer": containers[0]["type"] == "reefer",
"weight_tonnes": round(sum(c["weight_kg"] for c in containers) / 1000, 2),
},
"legs": [{
"mode": "sea",
"origin": {"unlocode": shipment["pol_locode"]},
"destination": {"unlocode": shipment["pod_locode"]},
"distance_km": shipment["route_nm"] * 1.852,
"vessel": {"imo": shipment["vessel_imo"], "size_teu": shipment.get("vessel_teu")},
"departure": shipment.get("pol_atd") or shipment.get("pol_etd"),
"arrival": shipment.get("pod_ata") or shipment.get("pod_eta"),
}],
}
r = requests.post(f"{os.environ['SWITCH_API_BASE']}/v1/emissions/shipment",
json=body, headers={"Authorization": f"Bearer {KEY}"}, timeout=30)
r.raise_for_status()
return r.json()
Call Switch again when your tracking data moves from estimated to actual dates. Each call creates a new result with a new id, and earlier results are kept unchanged. Store the latest id against your shipment.
A shipment is a transport chain: an ordered list of legs. Send one leg per transport segment, in order, with at least one leg.
One sea leg per vessel
When a container changes vessel at an intermediate port, send one sea leg per vessel, using the stops from your container route data. Each leg gets its own factor, so each vessel is calculated with its own factor and, when you send vessel.size_teu, its own size band.
- The
destinationof one leg is theoriginof the next. - Leave
distance_kmout on a sea leg and Switch calculates the shortest sea route between its two ports. Road and rail legs need a distance.
Example
{
"reference": "MSCU1234567",
"cargo": { "containers": 1, "teu_per_container": 2, "weight_tonnes": 18.5 },
"legs": [
{
"mode": "sea",
"origin": { "unlocode": "CNSHA" },
"destination": { "unlocode": "SGSIN" }
},
{
"mode": "sea",
"origin": { "unlocode": "SGSIN" },
"destination": { "unlocode": "NLRTM" },
"vessel": { "size_teu": 14000 }
},
{
"mode": "road",
"origin": { "unlocode": "NLRTM" },
"destination": { "unlocode": "DEDUS" },
"distance_km": 230
}
]
}Both sea legs here have no distance, so each comes back with distance_source: calculated and a warning that names the leg. The first sea leg has no vessel size, so the fleet average factor is used and a warning says so. Terminal handling at the transshipment port is not included in the result.
Modes you can mix
Legs can be sea, road, or rail. See Modes, vehicles and fuels.
How the signature works
X-Switch-Signature is the hex HMAC-SHA256 of the raw request body, using your webhook secret. Compute the same value from the bytes you received and compare. Use the raw body exactly as received. Parsing and re-serialising the JSON changes the bytes and the signature no longer matches.
import hashlib, hmac, os
SECRET = os.environ["SWITCH_WEBHOOK_SECRET"].encode()
def is_from_switch(raw_body: bytes, signature: str) -> bool:
"""raw_body: the request body exactly as received. signature: the X-Switch-Signature header."""
expected = hmac.new(SECRET, raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature or "")
import { createHmac, timingSafeEqual } from "node:crypto";
const SECRET = process.env.SWITCH_WEBHOOK_SECRET;
// rawBody: the request body exactly as received, as a Buffer
export function isFromSwitch(rawBody, signature) {
const expected = createHmac("sha256", SECRET).update(rawBody).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(signature || "");
return a.length === b.length && timingSafeEqual(a, b);
}
Compare with a constant-time function such as hmac.compare_digest or timingSafeEqual, as above. Keep the webhook secret on your server, like your API key.
Check a signature in your browser
Paste a raw body and your webhook secret to see the expected X-Switch-Signature. Add a received signature to compare.
Retries and duplicates
- A failed delivery is retried up to 6 times, after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 24 hours.
- Because of retries, the same event can arrive more than once or out of order. De-duplicate on
event_id. - Each event carries
created_at, so you can tell which update is the newest.
A webhook is a message Switch sends to your system when a result changes, instead of you asking for it. Register a webhook URL with your subscription. Switch sends an event when a running result changes and when it is final.
How it fits together
- You push a timestamp
PUT /v1/port-call/timestamps/{timestampID}returns202 Acceptedwith the running result ID. - Switch sends
emission.updatedWhenever a new timestamp changes the time split or CO₂. A timestamp that changes neither sends no event.
- Switch sends
emission.finalizedWhen the actual departure from berth arrives. The result is locked with its factor version.
- You fetch the final result
GET /v1/emissions/{id}returns the locked result.
Events
| Event | Sent when |
|---|---|
emission.updated | A new timestamp changes the time split or CO₂, for example when cargo operations complete and the idle clock starts. |
emission.finalized | The actual departure from berth arrives. The result is locked with its factor version and can be fetched with Retrieve a result. |
{
"event": "emission.updated",
"event_id": "evt_9Kd2mQ7xL4",
"created_at": "2026-11-23T18:00:04Z",
"id": "emi_3Pc8vR2tY6",
"port_call_id": "398d26ef-2f5f-4c5a-9bd0-6c67c7123bb5",
"status": "running",
"time": { "waiting_hours": 0.5, "berthing_hours": 1.5, "cargo_ops_hours": 5.0, "idle_hours": 0.0 },
"emissions": {
"total": { "co2_t": 5.45 },
"avoidable": { "co2_t": 0.39 }
},
"next_expected": "BERTH DEPA ACT"
}
Delivery
- Each delivery is signed with
X-Switch-Signature, the hex HMAC-SHA256 of the raw request body, using your webhook secret. - A delivery succeeds when your endpoint answers with a 2xx status within 10 seconds. Redirects are not followed, so register the final HTTPS address.
- A failed delivery is retried up to 6 times: after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 24 hours. After that it is marked as failed.
- Each delivery also carries
X-Switch-Eventwith the event name andX-Switch-Event-Idwith itsevent_id. - The same event can arrive more than once or out of order. De-duplicate on
event_id.
The scope boundary
Results are well-to-wake (WTW) by default: tank-to-wake, from running the vehicle or vessel, plus well-to-tank, from producing and delivering the fuel. Both parts are returned separately. Set options.scope to TTW for tank-to-wake only. Port-call results are tank-to-wake CO₂.
| Part | What it covers | Returned in |
|---|---|---|
| Tank-to-wake (TTW) | Burning the fuel while the vehicle or vessel runs. | ttw_co2e_kg |
| Well-to-tank (WTT) | Producing and delivering the fuel. | wtt_co2e_kg |
| Well-to-wake (WTW) | Both together. The default. | co2e_kg |
When the scope is WTW, each leg returns ttw_co2e_kg and wtt_co2e_kg, which add up to co2e_kg. The totals are total.ttw_co2e_kg and total.wtt_co2e_kg.
ISO 14083 reporting requires well-to-wake results. A tank-to-wake result is for internal analysis. When you request TTW, the response adds the warning Scope TTW requested; ISO 14083 reporting requires WTW.
Scopes in your report
For shippers and forwarders, all results are Scope 3 (Category 4, upstream transportation, or Category 9, downstream). For the operator of the vessel or truck, tank-to-wake fuel emissions are Scope 1 and well-to-tank is Scope 3 Category 3.
| You are | Tank-to-wake fuel | Well-to-tank |
|---|---|---|
| Shipper or forwarder | Scope 3, Category 4 or 9 | Scope 3, Category 4 or 9 |
| Operator of the vessel or truck | Scope 1 | Scope 3, Category 3 |
