How to Write Robust Code When Integrating Third‑Party APIs: A Real‑World Example

The article walks through a production scenario where business documents must be synchronized to a low‑code platform via its OpenAPI, explaining how to build a unified client, verify apparent failures, apply a single retry, and fall back to a task table for asynchronous recovery, all illustrated with concrete code.

samdeepthink
samdeepthink
samdeepthink
How to Write Robust Code When Integrating Third‑Party APIs: A Real‑World Example

In a business system, documents need to be synced in real time to a third‑party low‑code platform where partners perform shipping and approval. A missing response from the platform can cause a critical failure because customers would not see the document.

Unified Call Entry

The platform exposes a small set of methods— addRow, updateRow, and getRows. A LowCodeClient class wraps these calls so that the rest of the codebase only invokes the high‑level methods without dealing with HTTP details, logging, or exception handling.

GatewayRequestDTO req = buildRequest(apiName, appType, body);
JSONObject resp = JSON.parseObject(callGateway(req, apiName));
Object data = checkResponse(apiName, resp);
return data != null ? data.toString() : null;
buildRequest

assembles parameters, callGateway sends the HTTP request, and checkResponse validates the response. The platform returns a success flag; when false, an exception is thrown and caught by the caller.

Failure Does Not Always Mean Failure

When addRow times out or the gateway returns 500, many developers assume the write failed. In reality the request may have reached the platform and been persisted, but the response was lost due to network jitter, service restart, or gateway timeout.

Principle: If addRow appears to fail, do not immediately decide the outcome—first verify.

Query Confirmation

The platform provides a query API that can retrieve a record by business document number. After an exception, the code calls this query; finding the row means the write succeeded despite the missing response, and the existing rowId is returned. If the row is not found, the write truly failed.

Skipping this step can cause duplicate data when a retry blindly writes again, even though the platform may already have an idempotent guard.

Retry Once

When the query confirms a real failure, the code retries addRow only once. One retry is enough for transient network glitches; a second failure usually indicates a deeper issue, and further retries would only block the request and degrade system latency.

Fail fast and hand the problem to the background; it is far more reasonable than letting a real‑time request wait indefinitely.

Task Table Fallback

If the single retry still fails, the operation is recorded in a biz_task table for asynchronous, stepped retries (1 min, 5 min, 30 min, 2 h). When all retries exhaust, an alert is sent to a monitoring group for manual intervention.

CREATE TABLE biz_task (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(400) NOT NULL COMMENT 'task name',
    type VARCHAR(100) DEFAULT '' NOT NULL COMMENT 'task type',
    biz_id VARCHAR(200) DEFAULT '' NOT NULL COMMENT 'business ID',
    biz_type VARCHAR(100) NOT NULL COMMENT 'business type',
    retry_count INT UNSIGNED DEFAULT 0 NOT NULL COMMENT 'retry count',
    execute_result VARCHAR(20) COMMENT 'execution result',
    status VARCHAR(20) DEFAULT '' NOT NULL COMMENT 'status',
    trigger_time TIMESTAMP(3) COMMENT 'trigger time',
    priority INT DEFAULT 0 NOT NULL COMMENT 'priority',
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT 'create time',
    update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time'
) COMMENT 'business task';

This lightweight task framework avoids external message queues while providing reliable delayed retries.

Complete Flow

The end‑to‑end logic is:

Call LowCodeClient.addRow. If it succeeds, continue.

If an exception occurs, query the platform for the document number.

If the query finds the row, treat the operation as successful.

If not found, retry addRow once.

If the retry still fails, insert a record into biz_task for background retries and return null.

try {
    rowId = lowCodeClient.addRow(SHEET_ID, APP_TYPE, controls, false);
} catch (Exception e) {
    rowId = lowCodeClient.queryRowIdByBizNo(SHEET_ID, docNo);
    if (rowId == null) {
        try {
            rowId = lowCodeClient.addRow(SHEET_ID, APP_TYPE, controls, false);
        } catch (Exception retryEx) {
            // Write failure task, background scheduler retries in steps
            saveRetryTask(docNo, docType, controls);
        }
    }
}

The philosophy is to distrust any single call result: first confirm, then retry once, then delegate to asynchronous retries, and finally alert for human handling. In production, this mechanism has prevented document loss caused by brief platform outages, keeping customer complaints to a minimum.

Takeaway

Robust third‑party API integration is less about the code itself and more about the mindset of anticipating non‑functional failures that never appear in requirements. By systematically handling timeouts, false successes, limited retries, and graceful degradation, developers elevate from merely delivering features to building resilient systems.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backend developmenterror handlingAPI integrationlow-code platformretry logicrobust code
samdeepthink
Written by

samdeepthink

Knowledge Planet: Old Dock's Tech Chronicles Zhihu: SamDeepThinking A technical manager who still codes heavily on the front line. From junior developer to tech lead, then tech manager, now leading the whole front‑ and back‑end development team—leveling up along the way. I have some insights on programming, career development, and tech management.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.