Skip to main content

HTTP Response Codes

BIEASES Payment API uses standard HTTP response codes to indicate the success or failure of API requests. Understanding these codes is essential for proper error handling and debugging.

Success Responses

Status CodeDescriptionUsage
200 OKRequest successfulAll successful API operations
201 CreatedResource created successfullyPayment order creation
202 AcceptedRequest accepted for processingAsynchronous operations

Client Error Responses

Status CodeDescriptionCommon CausesAction Required
400 Bad RequestRequest format invalidMissing parameters, invalid JSONFix request format
401 UnauthorizedAuthentication failedInvalid credentials, signature issuesCheck authentication
403 ForbiddenAccess deniedInsufficient permissions, suspended accountContact support
404 Not FoundResource not foundInvalid endpoint, non-existent payment IDVerify resource exists
409 ConflictResource conflictDuplicate order number, concurrent operationsUse unique identifiers
422 Unprocessable EntityValidation failedBusiness rule violationsFix validation errors
429 Too Many RequestsRate limit exceededToo many API callsImplement rate limiting

Server Error Responses

Status CodeDescriptionTypical ScenariosRecommended Action
500 Internal Server ErrorServer processing errorSystem issues, database problemsRetry with exponential backoff
502 Bad GatewayGateway errorLoad balancer issuesRetry after short delay
503 Service UnavailableService temporarily unavailableMaintenance, overloadRetry with backoff
504 Gateway TimeoutRequest timeoutNetwork issues, slow processingRetry with longer timeout

Response Headers

Standard Headers

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 1234
Date: Wed, 17 Jun 2024 10:30:00 GMT
Server: BIEASES-API/1.0

Response Body Format

Success Response

{
"code": "20000",
"msg": "SUCCESS",
"data": {
"paymentId": "1754349465357123584",
"status": "pending",
"checkoutUrl": "https://pay.bieases.com/checkout/..."
}
}

Error Response

{
"code": "40001",
"msg": "Signature verification failed",
"data": null,
"details": {
"field": "sign",
"reason": "Invalid RSA signature format"
}
}

Error Handling Best Practices

1. Status Code Mapping

public class HttpStatusHandler {

public void handleResponse(int statusCode, String body) {
switch (statusCode) {
case 200:
case 201:
case 202:
handleSuccess(body);
break;
case 400:
handleBadRequest(body);
break;
case 401:
handleAuthenticationError(body);
break;
case 429:
handleRateLimit(body);
break;
case 500:
case 502:
case 503:
handleServerError(body);
break;
default:
handleUnexpectedError(statusCode, body);
}
}
}

2. Retry Logic

public class RetryPolicy {

public boolean shouldRetry(int statusCode) {
return statusCode == 429 || // Rate limit
statusCode == 500 || // Internal server error
statusCode == 502 || // Bad gateway
statusCode == 503 || // Service unavailable
statusCode == 504; // Gateway timeout
}

public long getRetryDelay(int attempt, int statusCode) {
if (statusCode == 429) {
// Use Retry-After header if available
return getRetryAfterHeader();
}

// Exponential backoff for server errors
return Math.min(1000 * (long) Math.pow(2, attempt), 30000);
}
}

3. Timeout Configuration

public class ApiClient {
private static final int CONNECT_TIMEOUT = 5000; // 5 seconds
private static final int READ_TIMEOUT = 30000; // 30 seconds

public HttpClient buildClient() {
return HttpClient.newBuilder()
.connectTimeout(Duration.ofMillis(CONNECT_TIMEOUT))
.build();
}
}

Debugging HTTP Issues

1. Request Logging

public void logRequest(HttpRequest request) {
logger.info("API Request: {} {}",
request.method(), request.uri());
logger.debug("Headers: {}", request.headers());
// Never log sensitive data like signatures or keys
}

2. Response Analysis

public void analyzeResponse(HttpResponse<String> response) {
int status = response.statusCode();

if (status >= 400) {
logger.error("API Error: Status={}, Body={}",
status, response.body());

// Check for rate limiting
if (status == 429) {
String retryAfter = response.headers()
.firstValue("X-RateLimit-Retry-After")
.orElse("unknown");
logger.warn("Rate limited. Retry after: {} seconds", retryAfter);
}
}
}

3. Health Checks

public class HealthChecker {

public boolean isApiHealthy() {
try {
// Simple health check endpoint
HttpResponse<String> response = httpClient.send(
HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/health"))
.build(),
HttpResponse.BodyHandlers.ofString()
);

return response.statusCode() == 200;
} catch (Exception e) {
logger.error("Health check failed", e);
return false;
}
}
}

Common Scenarios

Payment Creation Error

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
"code": "44008",
"msg": "Invalid amount value",
"data": null,
"details": {
"field": "paymentAmount",
"reason": "Amount must be positive and match order total"
}
}

Authentication Failure

HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
"code": "44001",
"msg": "Signature verification failed",
"data": null,
"details": {
"timestamp": "2024-06-17T10:30:00Z",
"merchantId": "B131567545069"
}
}

Rate Limit Exceeded

HTTP/1.1 429 Too Many Requests
Content-Type: application/json

{
"code": "42901",
"msg": "Rate limit exceeded. Try again in 60 seconds.",
"data": null
}

Next: Learn about specific API status codes and their meanings, or understand rate limiting policies.