Responses & Error Handling
Master how the 7G API communicates success, failure, and errors across all endpoints using consistent response structures.
For HTTP/REST users: Parse JSON responses and check result field (boolean) plus HTTP status codes
For .NET SDK users: Check response.Result property and handle HttpRequestException for HTTP-level errors
Both approaches use the same response structures - APIResponse for all endpoints except authentication (which uses TokenResponse).
Quick Reference
2 Response Structures
APIResponse (70 of 72 Endpoints)
Structure: { result, message, recordCount, data }
Fields:
result(bool) - Success indicatormessage(string) - Error detailsrecordCount(int) - Record countdata(dynamic) - Response payload
Used for: All GET, POST, PUT, DELETE operations
TokenResponse (2 Endpoints Only)
Structure: { accessToken, refreshToken }
Fields:
accessToken- JWT for API requestsrefreshToken- Long-lived renewal token
Used for: /User/Login, /User/RefreshToken only
NOT wrapped in APIResponse
Check the Status Code and the result Field
Check result: true to confirm success. Business logic errors (validation, not found, conflicts) return an HTTP 4xx status with result: false and the reason in message.
Error handling happens at TWO levels - HTTP status codes AND the result field.
Why This Matters
Proper error handling prevents data corruption, enables graceful degradation through retry logic, and provides clear feedback when operations fail. Critical for maintaining data integrity in financial services operations.
APIResponse Structure
Standard response format for all operational endpoints
Used for all endpoints except authentication (/User/Login and /User/RefreshToken).
Field Descriptions
| Field | Type | Description | When Populated |
|---|---|---|---|
result |
boolean | Success indicator (true = success, false = error) |
Always present |
message |
string | Error message explaining what went wrong | Only when result: false, null/empty when success |
recordCount |
integer | Number of records in current page (GET) or records affected (POST/PUT/DELETE) | List (GET) responses; not guaranteed on other responses or on errors |
data |
dynamic | Response payload (array for GET, object for POST/PUT, empty object for errors) | Always present (may be empty object {} on error) |
Critical: Always Check result Field
Business logic errors arrive with an HTTP 4xx status and result: false. Check the result field before processing data.
// HTTP Response (200 OK)
{
"result": true,
"message": "",
"recordCount": 3,
"data": [
{
"bizEntityID": 12345,
"name": "Smith Super Fund",
"bizEntityTypeID": 4
},
{
"bizEntityID": 12346,
"name": "Jones Trust",
"bizEntityTypeID": 2
},
{
"bizEntityID": 12347,
"name": "Wilson Family",
"bizEntityTypeID": 1
}
]
}TokenResponse Structure
Special format for authentication endpoints only
Critical Difference: Authentication endpoints (/User/Login and /User/RefreshToken) return TokenResponse directly, NOT wrapped in APIResponse.
Field Descriptions
| Field | Type | Description |
|---|---|---|
accessToken |
string | JWT bearer token used in Authorization header for all authenticated requests. Expires 20 minutes after issue. |
refreshToken |
string | Long-lived token used to obtain new access tokens without re-authentication. Each refresh returns a NEW refresh token (token rotation). |
No expiresIn Field
Unlike many APIs, TokenResponse does NOT include an expiresIn field. Tokens expire 20 minutes after issue:
- .NET SDK — Reads JWT
expclaim directly and auto-refreshes 30 seconds before expiry - HTTP/REST — Track expiry manually as
loginTimestamp + 20 minutes, or decode the JWTexpclaim. Refresh proactively around the 15-minute mark.
Public Endpoints (No Authentication Required)
Only 4 endpoints can be called without an Authorization header:
POST /user/login— Authenticate and receive tokensPOST /user/refreshToken— Exchange a refresh token for new tokensGET /common/lookup— Retrieve lookup categoriesGET /common/HealthCheck— Health monitoring
All other endpoints require authentication (valid access token in Authorization header). POST /user/refreshToken validates the refresh token in the request body; the Authorization header is optional there, and if you send your current access token it is revoked when the refresh succeeds.
// POST /User/Login - HTTP 200 OK
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "9z8y7x6w5v4u3t2s1r0q9p8o7n6m5l4k3j2i..."
}
// NOT wrapped in APIResponse - TokenResponse is returned directly
// Use accessToken in Authorization header for subsequent requestsAccess Control
API roles, product access, and the responses you get when either check fails
A valid access token is not enough on its own. Every authenticated request passes two further checks: your role must allow the endpoint, and the request must refer to a product you have that role on.
API Roles
API users are granted one or more of three roles, and each role is granted per product.
| Role | Read endpoints | Write endpoints | /Report endpoints |
|---|---|---|---|
API_Administrator |
Yes | Yes | Yes |
API_Readonly |
Yes | No | No |
API_Reports |
No | No | Yes |
- Read endpoints — every
GEToutside/Report, plusPOST /Document/Statement - Write endpoints — every other
POST,PUTandDELETEoutside/Report /Reportendpoints — all four report operations- A user who holds both
API_AdministratorandAPI_Readonlyon the same product is treated as read-only for that product - A user with none of the three roles cannot log in, and an access token that carries none of them is rejected with 401
Product Access
The API works out which product a request concerns from the identifiers it carries, then checks that you hold the required role on that product. It reads ProductID / ExternalProductId and also the identifiers of records that belong to a product — account, entity, investment, distribution, transaction, event, document, address, communication, payment detail, person and organisation IDs, in both their native and external forms.
| Situation | Response | What to do |
|---|---|---|
| An identifier points at a product you do not have the required role on | 403 — "The requested product is not available." | Check the identifier; ask your 7G administrator for access to that product |
| The request carries no identifier the API can use | 400 — "This request must reference a product (ProductID or ExternalProductId)." | Add ProductID or ExternalProductId to the request |
- Only exact values count. A plain value (
ProductID=100) or an.equalfilter is read. Filters that use.in, ranges or pattern operators are ignored for this check, as are numeric IDs of0. - List requests are the usual cause of the 400. A query that filters only on names, types, dates or
SecurityCodehas nothing the API can resolve to a product — includeProductIDorExternalProductIdalongside your filters. /personand/organisationaccept requests without an identifier, provided you hold the required role on at least one product./User,/Commonand/Reportare not product-scoped by this check. Report requests name their product in the report parameters instead — see POST /Report.
HTTP Status Codes
Understanding what each status code means and how to respond
Success Codes (2xx)
| Code | Name | When Returned | Response Body |
|---|---|---|---|
200 |
OK | Standard successful response for GET, PUT, DELETE | APIResponse with result: true (or TokenResponse for auth) |
201 |
Created | Resource successfully created via POST | APIResponse with result: true and created entity in data |
Client Errors (4xx)
| Code | Name | Common Causes | How to Fix |
|---|---|---|---|
400 |
Bad Request | Validation errors, missing required fields, invalid data format, request does not reference a product | Check request body against DTO requirements and validation rules; include ProductID or ExternalProductId |
401 |
Unauthorized | Missing token, expired token, invalid or malformed token, token carries no API role | Include Authorization header or refresh/re-login |
403 |
Forbidden | Your role does not allow the endpoint, or the request refers to a product you do not have access to | See Access Control; contact your 7G administrator to change roles or product access |
404 |
Not Found | Requested resource doesn't exist, or the route itself does not exist | Verify ID/external reference or check if resource was deleted; check the endpoint path |
409 |
Conflict | Duplicate key, unique constraint violation, relationship constraint, record changed by another user, database deadlock | Use unique identifiers, remove dependencies before deletion; reload and retry when the record was changed by someone else |
422 |
Unprocessable Entity | Idempotency key reused with a different request payload or endpoint (instances enrolled in idempotency only) | Generate a fresh Idempotency-Key for the new operation. See Idempotency. |
429 |
Too Many Requests | Rate limit exceeded | Implement exponential backoff and reduce request frequency |
Server Errors (5xx)
| Code | Name | When Returned | Recommended Action |
|---|---|---|---|
500 |
Internal Server Error | Unhandled exception or unexpected error | Log details and contact support if error persists after retry |
503 |
Service Unavailable | Database busy or temporarily unavailable | Retry with exponential backoff (wait 1s, 2s, 4s, etc.) |
504 |
Gateway Timeout | The database request timed out | Retry; narrow the request (filters, smaller pages) if it keeps timing out |
Error Messages Reference
Exact messages from the API and how to resolve them
Authentication Errors (401)
| Scenario | Exact Message | Solution |
|---|---|---|
| Missing Token | "Unauthorized: No authentication token was provided!" | Include Authorization header in request |
| Expired/Invalid Token | "Unauthorized: Expired or revoked Token was intercepted, Please login again!" | Use refresh token endpoint or re-login with credentials |
| Malformed Token | "Unauthorized: Malformed token, Please login again!" | Send the access token exactly as issued by login or refresh |
| No API Role | "Unauthorized: Your session has expired, Please login again!" | The token carries no API role — log in again; if login is refused, contact your 7G administrator |
| Refresh Failed | "Invalid or expired refresh token, Please login again!" | Log in again with credentials |
| Login Failed (400 - missing fields) | "Invalid credentials!" | Supply both username and password in the request body |
| Login Failed (401 - bad credentials) | Dynamic message from the authentication service (varies by failure cause — lockout, wrong password, disabled user, etc.) | Verify username/password; if locked, contact your 7G administrator |
| Login Failed (401 - no API role) | "Unable to login, This username does not have an authorised role to login!" | Ask your 7G administrator to grant the user an API role |
| Login Failed (401 - username not unique) | "Unable to login, This username is not unique, Please contact support!" | Contact 7G support |
Access Errors (400/403/404)
| Scenario | Exact Message | Solution |
|---|---|---|
| Role Does Not Allow Endpoint (403) | "Access Denied: You do not have access to this endpoint!" | The endpoint needs a role you do not hold — see API Roles |
| Product Not Accessible (403) | "The requested product is not available." | The request refers to a product you do not have the required role on |
| No Product Referenced (400) | "This request must reference a product (ProductID or ExternalProductId)." | Include ProductID or ExternalProductId — see Product Access |
| Unknown Endpoint (404) | "Not Found: The requested endpoint does not exist." | Check the path and its casing against the endpoint reference |
Validation Errors (400)
| Scenario | Message Pattern | Solution |
|---|---|---|
| FluentValidation | Varies by field/rule (e.g., "'Name' must not be empty", "Invalid email format") | Check validation requirements for each DTO field |
| Invalid Payload | "Invalid payload detected, [specific requirement]" | Verify request structure matches endpoint requirements |
| Missing Required Field | "A required field is missing : [tables]." — or "A required field is missing." when no table is named | Provide all required fields (non-nullable) |
| Invalid Data Format | "Invalid data format for one of the fields." | Check data types (string, int, date formats) |
| Value Out of Range | "A numeric or date value is out of range." | Verify value constraints (e.g., dates not in future, positive numbers) |
Conflict Errors (409)
| Scenario | Exact Message Pattern | Solution |
|---|---|---|
| Duplicate Key | "A record with the same key or unique value already exists : [tables]." | Use different external ID or check if record already exists |
| Relationship Constraint | "Cannot delete or update this record because it is linked in other entities : [tables]." | Remove dependent records first or use archive/soft delete |
| Database Deadlock | "The request could not be completed due to a database deadlock. Please retry." | Retry request - deadlocks are transient and resolve automatically |
| Concurrent Update | "The record was modified by another user. Please reload and try again." | Fetch the record again, re-apply your change and resubmit |
[tables] is the comma-separated list of database tables named in the underlying error. When no table is named, the message ends with a full stop instead (for example A record with the same key or unique value already exists.).
Server Errors (500/503/504)
| Status | Exact Message | Solution |
|---|---|---|
500 |
"An internal server error occurred while processing the request. Please try again later!" | Log error details and contact support if persists after retry |
503 |
"The database is busy. Please try again later." | Implement exponential backoff retry (1s, 2s, 4s, 8s) |
503 |
"The database is temporarily unavailable. Please try again later." | Wait and retry - typically resolves within seconds/minutes |
504 |
"The database request timed out. Please try again." | Retry; narrow the request (filters, smaller pages) if it keeps timing out |
Error Response Format
All error responses include:
{
"result": false,
"message": "[error message from tables above]",
"data": {}
}Even for HTTP 4xx/5xx errors, the response body follows this structure with result: false and descriptive message. recordCount is not part of the error format — a few list endpoints include recordCount: 0 on a validation error, but do not rely on it.
Error Handling Strategies
Path-specific approaches for robust error recovery
HTTP/REST Approach
Manual two-level error handling with explicit status code checking and response parsing.
Strategy
- Level 1: Check HTTP status code (200, 400, 401, 500, 503, etc.)
- Level 2: Parse JSON response body and check
resultfield - Implement manual retry logic for 503 errors with exponential backoff
- Track token expiry and refresh proactively (5 minutes before expiry)
// Complete HTTP/REST error handling pattern
using System.Net.Http;
using System.Net.Http.Json;
try
{
var response = await httpClient.GetAsync("/BizEntity?ProductID=100&PageSize=10");
// Level 1: Check HTTP status code
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
Console.WriteLine("Token expired - refreshing...");
await RefreshTokenAsync();
response = await httpClient.GetAsync("/BizEntity?ProductID=100&PageSize=10");
}
else if (response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
{
Console.WriteLine("Service busy - retrying with backoff...");
await Task.Delay(1000); // 1 second
response = await httpClient.GetAsync("/BizEntity?ProductID=100&PageSize=10");
}
// Level 2: Parse response body
var result = await response.Content.ReadFromJsonAsync<APIResponse>();
// Check business logic success (even if HTTP 200)
if (!result.Result)
{
Console.WriteLine($"Business error: {result.Message}");
return;
}
// Success - process data
Console.WriteLine($"Success! Retrieved {result.RecordCount} entities");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}.NET SDK Approach
Layered error handling with exceptions for HTTP errors and result checking for business logic.
Strategy
- Level 1: Catch
HttpRequestExceptionfor HTTP-level errors (401, 500, network failures) - Level 2: Check
response.Resultfor business logic errors (validation, not found, conflicts) - SDK handles token refresh automatically (30 seconds before expiry)
- Built-in retry logic for token expiry scenarios
// Complete SDK error handling pattern
using SevenG.API.SDK;
using System.Net;
try
{
var filter = new BizEntityFilter { ProductID = 100, PageSize = 10 };
var response = await client.BizEntity.GetAsync(filter);
// Level 2: Check business logic success
if (!response.Result)
{
Console.WriteLine($"Business error: {response.Message}");
// Handle specific business errors
if (response.Message.Contains("not found"))
{
Console.WriteLine("Entity doesn't exist");
}
else if (response.Message.Contains("already exists"))
{
Console.WriteLine("Duplicate record detected");
}
return;
}
// Success - deserialize and process
var entities = JsonSerializer.Deserialize<List<BizEntityDTO>>(
JsonSerializer.Serialize(response.Data),
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
);
Console.WriteLine($"Success! Retrieved {entities.Count} entities");
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Authentication failed - token expired");
// SDK auto-refreshes, so this means refresh also failed
await client.Auth.LoginAsync(username, password);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.ServiceUnavailable)
{
Console.WriteLine("Service temporarily unavailable - retry with backoff");
await Task.Delay(2000); // 2 seconds
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP error {ex.StatusCode}: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}Universal Best Practices
Strategies that apply regardless of integration approach.
- Layered handling - HTTP errors → Business logic errors → Application errors
- Exponential backoff - For 503 errors, wait 1s, then 2s, 4s, 8s between retries
- Log exact messages - Capture
response.messagefor debugging and support - Never retry 400 errors - Validation failures won't succeed on retry
- Check recordCount - Handle empty result sets (
recordCount: 0) gracefully - Monitor token expiry - Refresh tokens before they expire to avoid 401s mid-operation
Error Recovery Decision Tree
| If You Receive | Then | Reason |
|---|---|---|
| HTTP 401 | Refresh token or re-login | Token missing, expired, or invalid |
| HTTP 400 | Fix request payload | Validation error or missing required field |
| HTTP 409 | Check for duplicates/dependencies | Unique constraint or relationship violation |
| HTTP 500 | Log and retry once, then contact support | Unexpected server error |
| HTTP 503 | Retry with exponential backoff | Database busy or temporarily unavailable (transient) |
| Any 4xx + result: false | Check message for details |
Business logic error (not found, validation, etc.) |
Response Processing Patterns
How to work with response.Data effectively
Pattern 1: Deserializing Collections (.NET)
The SDK returns response.Data as dynamic. Convert to strongly-typed collections:
var response = await client.BizEntity.GetAsync(filter);
if (response.Result)
{
// Deserialize to List<BizEntityDTO>
var entities = JsonSerializer.Deserialize<List<BizEntityDTO>>(
JsonSerializer.Serialize(response.Data),
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
);
foreach (var entity in entities)
{
Console.WriteLine($"{entity.BizEntityID}: {entity.Name}");
}
}
else
{
Console.WriteLine($"Error: {response.Message}");
}Pattern 2: Handling Empty Results
Check recordCount to detect empty result sets before processing:
var response = await client.BizEntity.GetAsync(filter);
if (!response.Result)
{
Console.WriteLine($"Error: {response.Message}");
return;
}
// Check for empty results
if (response.RecordCount == 0)
{
Console.WriteLine("No entities found matching your filter");
return;
}
// Process data knowing it's not empty
var entities = JsonSerializer.Deserialize<List<BizEntityDTO>>(
JsonSerializer.Serialize(response.Data),
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
);
Console.WriteLine($"Found {entities.Count} entities");Pattern 3: Single vs Multiple Records
Understand when data is an array vs single object:
| Endpoint Type | Data Format | Example |
|---|---|---|
| GET (collection) | Array of objects | GET /BizEntity → data: [...] |
| POST (create) | Single object | POST /BizEntity → data: {...} |
| PUT (update) | Single object | PUT /BizEntity → data: {...} |
| DELETE | null (no payload) |
DELETE /Person → data: null |
Detection Tip: Check recordCount - if it's 0 or 1, you likely have a single object. If > 1, it's an array.
Best Practices
Guidelines for robust error handling and response processing
Recommended
- Always check
response.Resultbefore processing data (even if HTTP 200) - Log exact error messages from
response.Messagefor debugging - Implement exponential backoff for 503 errors (1s, 2s, 4s, 8s)
- Handle both HTTP-level errors (exceptions) and business logic errors (
result: false) - Check
recordCountto handle empty result sets gracefully - Refresh tokens proactively before expiry (SDK: 30s, HTTP: 5min)
- Validate request payloads before sending to avoid 400 errors
Avoid
- Assuming HTTP 200 means success (always check
resultfield) - Ignoring the
messagefield when debugging errors - Processing
datawithout checkingresultfirst - Hardcoding error messages (they may evolve with API versions)
- Retrying 400 errors (validation failures won't succeed on retry)
- Letting tokens expire during operations (causes disruptive 401 errors)
- Treating all errors the same (different codes require different strategies)