REST APIs for ecommerce integrations: authentication, limits and errors
Integrations almost always fail for the same reasons: expired tokens, request limits and unhandled errors. We give you the guidelines to avoid them.
Almost all of a store's integrations talk to REST APIs: the ERP's, the payment gateway's, the carrier's, the store's own. These guidelines avoid most problems.
Authentication
- API keys: simple. Keep them out of the code (encrypted configuration, environment variables) and use one per integration.
- OAuth2: tokens that expire. Renew the token before it expires and handle the 401 error by renewing and retrying once.
- Never send credentials over unencrypted HTTP or in the URL.
Pagination and filters
Do not ask for “all orders”. Ask for those modified since the last synchronisation, in pages. Store the timestamp of the last successful synchronisation, not of the last attempted one.
Request limits
Most APIs limit how many requests you can make per minute. When you exceed it, they respond with 429. Respect the Retry-After header and wait with an increasing delay.
for ($intento = 0; $intento < 5; $intento++) {
$r = llamar($url);
if ($r->status !== 429 && $r->status < 500) {
break;
}
sleep(min(60, 2 ** $intento));
}
Errors
- 4xx: the error is yours (malformed data, no permission). Do not retry without fixing it.
- 5xx and timeouts: retry with a wait.
- Log the request and the response (without sensitive data) for every error.