REST API GUIDE

wechess-leaderboard-service

Version: 1.0.21

Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the Leaderboard Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our Leaderboard Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the Leaderboard Service via HTTP requests for purposes such as creating, updating, deleting and querying Leaderboard objects.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST It’s important to note that the Leaderboard Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.

Authentication And Authorization

To ensure secure access to the Leaderboard service’s protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it’s important to note that access control varies across different routes:

Protected API: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.

**Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.

Token Locations

When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.

Location Token Name / Param Name
Query access_token
Authorization Header Bearer
Header wechess-access-token
Cookie wechess-access-token

Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.

Api Definitions

This section outlines the API endpoints available within the Leaderboard service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It’s important to understand the flexibility in how parameters can be included in requests to effectively interact with the Leaderboard service.

This service is configured to listen for HTTP requests on port 3001, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

This service is accessible via the following environment-specific URLs:

Parameter Inclusion Methods: Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:

Query Parameters: Included directly in the URL’s query string.

Path Parameters: Embedded within the URL’s path.

Body Parameters: Sent within the JSON body of the request.

Session Parameters: Automatically read from the session object. This method is used for parameters that are intrinsic to the user’s session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.

Note on Session Parameters: Session parameters represent a unique method of parameter inclusion, relying on the context of the user’s session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.

By adhering to the specified parameter inclusion methods, you can effectively utilize the Leaderboard service’s API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.

Common Parameters

The Leaderboard service’s business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.

Supported Common Parameters:

By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the Leaderboard service.

Error Response

If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Object Structure of a Successfull Response

When the Leaderboard service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.

Key Characteristics of the Response Envelope:

Design Considerations: The structure of a API’s response data is meticulously crafted during the service’s architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.

Brief Data: Certain API’s return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.

API Response Structure

The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling the successful execution of the request. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Handling Errors:

For details on handling error scenarios and understanding the structure of error responses, please refer to the “Error Response” section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.

Resources

Leaderboard service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.

PlayerStats resource

Resource Definition : Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user. PlayerStats Resource Properties

Name Type Required Default Definition
userId ID The registered user this record belongs to (auth:user.id).
eloRating Integer Current ELO rating for registered player.
totalGames Integer Total completed games (wins + losses + draws) for this player.
wins Integer Number of games won by the player.
losses Integer Number of games lost by the player.
draws Integer Number of drawn games by the player.
streak Integer Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt Date Timestamp of last completed game for user.
username String Display name for the player, publicly visible.

LeaderboardEntry resource

Resource Definition : Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests. LeaderboardEntry Resource Properties

Name Type Required Default Definition
userId ID The registered user this leaderboard entry represents.
currentRank Integer Current leaderboard rank (1=top). Lower is better.
eloRating Integer Player's current ELO rating (copy from playerStats).
season String Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt Date Timestamp of last rank change/leaderboard update.
username String Display name for the player, publicly visible on leaderboard.

Business Api

Create Playerstats API

[Default create API] — This is the designated default create API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a player stats record for a newly registered player. Only registered users (never guests) should have this object. Typically used at registration or conversion.

API Frontend Description By The Backend Architect

Called only at registration or on converting guest to registered. Prepares stats for profile display.

Rest Route

The createPlayerStats API REST controller can be triggered via the following route:

/v1/playerstatses

Rest Request Parameters

The createPlayerStats api has got 9 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
eloRating Integer true request.body?.[“eloRating”]
totalGames Integer true request.body?.[“totalGames”]
wins Integer true request.body?.[“wins”]
losses Integer true request.body?.[“losses”]
draws Integer true request.body?.[“draws”]
streak Integer true request.body?.[“streak”]
lastGameAt Date false request.body?.[“lastGameAt”]
username String false request.body?.[“username”]
userId : The registered user this record belongs to (auth:user.id).
eloRating : Current ELO rating for registered player.
totalGames : Total completed games (wins + losses + draws) for this player.
wins : Number of games won by the player.
losses : Number of games lost by the player.
draws : Number of drawn games by the player.
streak : Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt : Timestamp of last completed game for user.
username : Display name for the player, publicly visible.

REST Request To access the api you can use the REST controller with the path POST /v1/playerstatses

  axios({
    method: 'POST',
    url: '/v1/playerstatses',
    data: {
            userId:"ID",  
            eloRating:"Integer",  
            totalGames:"Integer",  
            wins:"Integer",  
            losses:"Integer",  
            draws:"Integer",  
            streak:"Integer",  
            lastGameAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "playerStats",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"id": "ID",
		"userId": "ID",
		"eloRating": "Integer",
		"totalGames": "Integer",
		"wins": "Integer",
		"losses": "Integer",
		"draws": "Integer",
		"streak": "Integer",
		"lastGameAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Playerstats API

[Default update API] — This is the designated default update API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update player statistics when a game completes. Only called for registered users by gameplay service (M2M) or admin; guests not allowed.

API Frontend Description By The Backend Architect

System/gameplay triggers this to update stats at game end. Never called for guests.

Rest Route

The updatePlayerStats API REST controller can be triggered via the following route:

/v1/playerstatses/:playerStatsId

Rest Request Parameters

The updatePlayerStats api has got 9 regular request parameters

Parameter Type Required Population
playerStatsId ID true request.params?.[“playerStatsId”]
eloRating Integer true request.body?.[“eloRating”]
totalGames Integer true request.body?.[“totalGames”]
wins Integer true request.body?.[“wins”]
losses Integer true request.body?.[“losses”]
draws Integer true request.body?.[“draws”]
streak Integer true request.body?.[“streak”]
lastGameAt Date false request.body?.[“lastGameAt”]
username String false request.body?.[“username”]
playerStatsId : This id paremeter is used to select the required data object that will be updated
eloRating : Current ELO rating for registered player.
totalGames : Total completed games (wins + losses + draws) for this player.
wins : Number of games won by the player.
losses : Number of games lost by the player.
draws : Number of drawn games by the player.
streak : Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt : Timestamp of last completed game for user.
username : Display name for the player, publicly visible.

REST Request To access the api you can use the REST controller with the path PATCH /v1/playerstatses/:playerStatsId

  axios({
    method: 'PATCH',
    url: `/v1/playerstatses/${playerStatsId}`,
    data: {
            eloRating:"Integer",  
            totalGames:"Integer",  
            wins:"Integer",  
            losses:"Integer",  
            draws:"Integer",  
            streak:"Integer",  
            lastGameAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "playerStats",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"id": "ID",
		"userId": "ID",
		"eloRating": "Integer",
		"totalGames": "Integer",
		"wins": "Integer",
		"losses": "Integer",
		"draws": "Integer",
		"streak": "Integer",
		"lastGameAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Playerstats API

[Default get API] — This is the designated default get API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single registered user’s player stats (private to user or admin).

API Frontend Description By The Backend Architect

Used to display profile stats. User can only view own; admin can view any.

Rest Route

The getPlayerStats API REST controller can be triggered via the following route:

/v1/playerstatses/:userId

Rest Request Parameters

The getPlayerStats api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : The registered user this record belongs to (auth:user.id)… The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/playerstatses/:userId

  axios({
    method: 'GET',
    url: `/v1/playerstatses/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "playerStats",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"isActive": true
	}
}

Get Leaderboardentry API

[Default get API] — This is the designated default get API for the leaderboardEntry data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch this player’s leaderboard rank entry (registered users only).

API Frontend Description By The Backend Architect

Allow user to view their own leaderboard position (or admin to view any user). Entry includes user info for display.

Rest Route

The getLeaderboardEntry API REST controller can be triggered via the following route:

/v1/leaderboardentries/:userId

Rest Request Parameters

The getLeaderboardEntry api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : The registered user this leaderboard entry represents… The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/leaderboardentries/:userId

  axios({
    method: 'GET',
    url: `/v1/leaderboardentries/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "leaderboardEntry",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"leaderboardEntry": {
		"isActive": true
	}
}

List Leaderboardtopn API

[Default list API] — This is the designated default list API for the leaderboardEntry data object. Frontend generators and AI agents should use this API for standard CRUD operations. List top N players for leaderboard display (e.g., leaderboard page top 100). Sorted by currentRank ascending (best = 1).

API Frontend Description By The Backend Architect

Leaderboard screen populates using this API; accessible to all authenticated users (guests see empty/null result).

Rest Route

The listLeaderboardTopN API REST controller can be triggered via the following route:

/v1/leaderboardtopn

Rest Request Parameters

The listLeaderboardTopN api has got 1 regular request parameter

Parameter Type Required Population
topN Integer false request.query?.[“topN”]
topN : Number of top players to return (max 500)

REST Request To access the api you can use the REST controller with the path GET /v1/leaderboardtopn

  axios({
    method: 'GET',
    url: '/v1/leaderboardtopn',
    data: {
    
    },
    params: {
             topN:'"Integer"',  
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "leaderboardEntries",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"leaderboardEntries": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Leaderboardentry API

Create a leaderboard entry for a registered player. Called when PlayerStats exists but LeaderboardEntry is missing.

API Frontend Description By The Backend Architect

Called by ensureLeaderboardEntry when a user has PlayerStats but no LeaderboardEntry.

Rest Route

The createLeaderboardEntry API REST controller can be triggered via the following route:

/v1/leaderboardentries

Rest Request Parameters

The createLeaderboardEntry api has got 6 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
currentRank Integer true request.body?.[“currentRank”]
eloRating Integer true request.body?.[“eloRating”]
season String false request.body?.[“season”]
lastRankChangeAt Date false request.body?.[“lastRankChangeAt”]
username String false request.body?.[“username”]
userId : The registered user this leaderboard entry represents.
currentRank : Current leaderboard rank (1=top). Lower is better.
eloRating : Player’s current ELO rating (copy from playerStats).
season : Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt : Timestamp of last rank change/leaderboard update.
username : Display name for the player, publicly visible on leaderboard.

REST Request To access the api you can use the REST controller with the path POST /v1/leaderboardentries

  axios({
    method: 'POST',
    url: '/v1/leaderboardentries',
    data: {
            userId:"ID",  
            currentRank:"Integer",  
            eloRating:"Integer",  
            season:"String",  
            lastRankChangeAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "leaderboardEntry",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"leaderboardEntry": {
		"id": "ID",
		"userId": "ID",
		"currentRank": "Integer",
		"eloRating": "Integer",
		"season": "String",
		"lastRankChangeAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .