psn-api Documentation
website·Indexed 31 days ago
https://psn-api.achievements.app/A JavaScript library for retrieving trophy, user, and game data from the PlayStation Network. Documentation includes guides on authentication flows using access and refresh tokens, universal search, and functions such as getProfileFromUserName, getTitleTrophies, and getUserTrophyGroupEarningsForTitle.
What's inside psn-api
- psn-api is a low-level JavaScript library used to retrieve trophy, user, and game data from the PlayStation Network. Unlike high-level wrappers, psn-api follows a UNIX-like philosophy where each function performs a single API call. This design ensures the library remains small (under 3Kb), easy to compose, and resilient to changes in Sony's API. It includes native TypeScript support and maintains 100% test coverage.
Understand the RarestThinTrophy data model
TheRarestThinTrophyentity is a lightweight subset of the full Trophy model. It is typically returned when calling thegetUserTrophiesEarnedForTitle()function. It contains essential metadata about a trophy's identity, earn status, and rarity without the full trophy details.interface RarestThinTrophy { trophyId: number; // Unique ID for this trophy (unique within the title) trophyHidden: boolean; // True if this is a secret trophy earned: boolean; // True if this trophy has been earned trophyType: "bronze" | "silver" | "gold" | "platinum"; // The trophy grade trophyRare: TrophyRarity; // Rarity of the trophy trophyEarnedRate: string; // Percentage of all users who have earned the trophy }Reference the Trophy data model
The Trophy object represents a specific achievement within a game title. It contains metadata about the trophy's requirements, its rarity, and the user's earning status.interface Trophy { trophyId: number; // Unique ID for this trophy trophyHidden: boolean; // True if it is a secret trophy trophyType: "bronze" | "silver" | "gold" | "platinum"; // The trophy grade earned: boolean; // True if the trophy has been earned earnedDateTime: string; // ISO 8601 string (e.g., "2021-08-15T21:22:08Z"). Only returned if earned is true trophyDetail: string; // Description of the trophy trophyEarnedRate: string; // Percentage of all users who earned the trophy trophyGroupId: string; // "default" for standard set, or numeric (e.g., "001") for DLC trophyIconUrl: string; // URL for the trophy graphic trophyName: string; // Name of the trophy trophyProgressTargetValue: string; // Total required for unlock (PS5 titles only, if progress is tracked) trophyRare: TrophyRarity; // Rarity of the trophy trophyRewardImageUrl: string; // URL for reward graphic (PS5 titles only, if reward exists) trophyRewardName: string; // Name of the reward (PS5 titles only, if reward exists) }Recently Played Game data model
The Recently Played Game object provides details about a game a user has recently played, including timestamps, platform information, and identifiers used to link to the PlayStation Store.interface RecentlyPlayedGame { name: string; // The name of the game lastPlayedDateTime: string; // ISO date of last play (e.g., 2023-03-10T01:01:01.390000Z) conceptId: string; // ID used in store.playstation.com/en-is/concept/:conceptId titleId: string; // Product ID used in store.playstation.com/en-us/product/UP9000-$titleId-... platform: TitlePlatform | "UNKNOWN"; // Platform played on. "UNKNOWN" may appear if multiple users share a console entitlementId: string | null; // Used in store.playstation.com/en-ae/product/:entitlementId (primarily PS4) productId: string | null; // Product ID used in Store URLs (primarily PS4) image: { url: string; // URL to the game icon file }; }Trophy Title data model reference
The Trophy Title object provides metadata about a game's trophy set and the authenticating user's progress. Key fields include:
npServiceName: Indicates the platform family. Usetrophyfor PS3, PS4, or PS Vita; usetrophy2for PS5.npCommunicationId: The unique identifier for the title, required to request detailed trophy information.trophyTitleName: The name of the game.trophyTitlePlatform: The platform(s) the title belongs to (comma-separated if shared, e.g., "PS4,PSVITA").progress: The percentage of trophies earned by the user (e.g., 100, 25).hasTrophyGroups: Boolean indicating if the title contains trophy groups beyond the default group.hiddenFlag: Boolean indicating if the title is hidden on the authenticating account's trophy list.lastUpdatedDateTime: ISO 8601 string of when the most recent trophy was earned (e.g., "2021-08-15T21:22:08Z").trophyTitleIconUrl: URL to the title's icon.trophySetVersion: The current version of the trophy set.definedTrophies: ATrophyCountsobject containing the total number of trophies by type.earnedTrophies: ATrophyCountsobject containing the number of trophies earned by grade.trophyTitleDetail: Legacy description property for PS3, PS4, and PS Vita titles.
Reference the TitleThinTrophy data model
TheTitleThinTrophyentity is a lightweight subset of the full Trophy model, typically returned by thegetTitleTrophies()function. It contains essential metadata about a trophy within a specific game title.interface TitleThinTrophy { trophyId: number; // Unique ID for this trophy (unique within the title) trophyHidden: boolean; // True if it is a secret trophy trophyType: "bronze" | "silver" | "gold" | "platinum"; // The trophy grade trophyName: string; // Name of the trophy trophyDetail: string; // Description of the trophy trophyIconUrl: string; // URL for the trophy graphic trophyGroupId: string; // ID of the trophy group ("default" for standard set, "001", "002" etc. for DLC) }Understand the AccountDevice data model
TheAccountDeviceobject represents a specific device associated with a PlayStation account. It contains details about the hardware platform, activation status, and internal PlayStation identifiers.interface AccountDevice { deviceId: string; // The unique device identifier deviceType: string; // The device type/platform (e.g., PS5, PS4, PS3, PSVita) activationType: string; // The activation type for the device (e.g., PRIMARY, PSN_GAME_V3) activationDate: string; // The device activation date in ISO 8601 format (e.g., 2023-06-03T21:25:28.987Z) accountDeviceVector: string; // The account device vector (internal PlayStation identifier) }User profile titles object schema
When retrieving a user profile viagetProfileFromUserNameorgetProfileFromAccountId, thetitlesarray contains objects representing the games played by the user. Each title object includes metadata about the game version, ownership, play statistics, and associated media.interface Title { titleId: string; // Example: "CUSA01433_00" name: string; // Example: "Rocket League®" localizedName: string; imageUrl: string; localizedImageUrl: string; category: "ps4_game" | "ps5_native_game" | "pspc_game" | "unknown"; service: "none" | "none_purchased" | "ps_plus"; // Ownership type playCount: number; firstPlayedDateTime: string; // ISO 8601 format lastPlayedDateTime: string; // ISO 8601 format media: { screenshotUrl?: string; [key: string]: string | undefined; }; concept: { id: number; titleIds: string[]; name: string; media: { audios: any[]; videos: any[]; images: Array<{ url: string; format: string; type: string; }>; }; }; }Retrieve the trophy list for a game title using getTitleTrophies
Use the
getTitleTrophiesfunction to retrieve the trophy list for a specific game title. You can fetch trophies for a specific group (e.g., DLC) or all groups by settingtrophyGroupIdto"all".Platform Requirements:
- For PS3, PS4, or PS Vita titles, you must set
npServiceNameto"trophy"in the options object. - For PS5 titles,
npServiceNameis optional (defaults to"trophy2").
import { getTitleTrophies } from "psn-api"; // Example: Get all trophies for a PS3 game (Red Dead Redemption) const ps3Response = await getTitleTrophies(authorization, "NPWR00867_00", "all", { npServiceName: "trophy" }); // Example: Get all trophies for a PS5 game (Astro's Playroom) const ps5Response = await getTitleTrophies(authorization, "NPWR20188_00", "all");- For PS3, PS4, or PS Vita titles, you must set
Refresh the psn-api access token using a refresh token
Access tokens in psn-api are short-lived. To obtain a new access token without requiring the user to re-authenticate via the PlayStation website, use the
exchangeRefreshTokenForAuthTokens()function.The typical workflow is:
- Check the
expiresInvalue (obtained from the initialexchangeAccessCodeForAuthTokens()call) to determine if the currentaccessTokenhas expired. - If expired, call
exchangeRefreshTokenForAuthTokens()passing the storedrefreshToken. - Use the new
accessTokenfrom the resulting authorization object for subsequent API calls.
// Initial authentication const authorization = await exchangeAccessCodeForAuthTokens(accessCode); // Calculate and store expiration date const now = new Date(); const expirationDate = new Date( now.getTime() + authorization.expiresIn * 1000 ).toISOString(); // ... later, check if expired ... const isAccessTokenExpired = new Date(expirationDate).getTime() < new Date().getTime(); if (isAccessTokenExpired) { // Use the refresh token to get a new access token const updatedAuthorization = await exchangeRefreshTokenForAuthTokens( authorization.refreshToken ); // Store the new accessToken and update the expirationDate using updatedAuthorization.expiresIn }- Check the
Make authenticated requests to the PSN API
All API functions in thepsn-apilibrary require an authorization object as their first argument. The functions specifically require theaccessTokenproperty from the authorization object to validate the request.// Example: Retrieve a list of games the user has earned trophies for const trophyTitlesResponse = await getUserTitles( { accessToken: authorization.accessToken }, "me" );Exchange an NPSSO token for an access code
TheexchangeNpssoForAccessCodefunction converts a 64-digit NPSSO token into an access code. This access code is a prerequisite for callingexchangeAccessCodeForAuthTokensto obtain API tokens.import { exchangeNpssoForAccessCode } from "psn-api"; const accessCode = await exchangeNpssoForAccessCode("<my 64-digit NPSSO>"); console.log(accessCode); // Example output: "v3.ABCDEF"