IZI SDK Examples: JavaScript and Python
เนื้อหานี้ยังไม่มีในภาษาของคุณ
IZI SDK Examples: JavaScript and Python
Section titled “IZI SDK Examples: JavaScript and Python”IZI has no official SDK — the API is standard GraphQL and works with any HTTP client. Below are wrapper classes for Node.js and Python: club employee sign-in, queries, and signing in again when the token has expired.
The IZI API has no token refresh: once a token expires, protected fields answer Unauthorized and you have to sign in again. The wrappers below do that once and retry the request.
Every operation in the IZI API must have a name (query GetClub { ... }) — the server rejects unnamed operations.
JavaScript / Node.js
Section titled “JavaScript / Node.js”Dependencies
Section titled “Dependencies”npm install graphql-request graphqlIZIClient Class
Section titled “IZIClient Class”const { GraphQLClient, gql } = require("graphql-request");
// Address of the contour where the club is registered: see "IZI API: Overview"const API_URL = process.env.IZI_API_URL || "https://api.x.izi.is/graphql";
const LOGIN = gql` mutation Login( $email: EmailAddress! $password: String! $countryCode: CountryCode! ) { loginWithEmailPassword( email: $email password: $password countryCode: $countryCode ) { accessToken } }`;
class IZIClient { constructor({ email, password, countryCode }) { this.credentials = { email, password, countryCode }; this.client = new GraphQLClient(API_URL); }
async login() { const data = await this.client.request(LOGIN, this.credentials); this.client.setHeader( "Authorization", `Bearer ${data.loginWithEmailPassword.accessToken}`, ); }
async request(document, variables = {}) { try { return await this.client.request(document, variables); } catch (error) { const code = error.response?.errors?.[0]?.extensions?.code;
// Token expired: there is no token refresh — sign in again and retry once if (code === "Unauthorized") { await this.login(); return await this.client.request(document, variables); }
throw error; } }}
module.exports = IZIClient;const IZIClient = require("./izi-client");const { gql } = require("graphql-request");
async function main() { const izi = new IZIClient({ email: process.env.IZI_EMAIL, password: process.env.IZI_PASSWORD, countryCode: process.env.IZI_COUNTRY_CODE, });
await izi.login();
const clubId = process.env.IZI_CLUB_ID;
// Club card const { club } = await izi.request( gql` query GetClub($clubId: ID!) { club(id: $clubId) { id name timezone } } `, { clubId }, );
console.log("Club:", club.name);
// Sessions in progress const { sessions } = await izi.request( gql` query StartedSessions($clubId: ID!) { sessions(filters: { clubId: $clubId, statuses: [STARTED] }) { items { id actualStartAt plannedEndAt } totalCount } } `, { clubId }, );
console.log("Sessions in progress:", sessions.totalCount);}
main().catch(console.error);Apollo Client (React / Next.js)
Section titled “Apollo Client (React / Next.js)”import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";import { setContext } from "@apollo/client/link/context";
const httpLink = createHttpLink({ uri: "https://api.x.izi.is/graphql",});
const authLink = setContext((_, { headers }) => { const token = localStorage.getItem("izi_access_token"); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : "", }, };});
export const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache(),});Python
Section titled “Python”Dependencies
Section titled “Dependencies”pip install gql[httpx] httpxIZIClient Class
Section titled “IZIClient Class”import osfrom gql import gql, Clientfrom gql.transport.exceptions import TransportQueryErrorfrom gql.transport.httpx import HTTPXTransport
# Address of the contour where the club is registered: see "IZI API: Overview"API_URL = os.environ.get("IZI_API_URL", "https://api.x.izi.is/graphql")
LOGIN = gql(""" mutation Login($email: EmailAddress!, $password: String!, $countryCode: CountryCode!) { loginWithEmailPassword(email: $email, password: $password, countryCode: $countryCode) { accessToken } }""")
class IZIClient: def __init__(self, email: str, password: str, country_code: str): self.credentials = {"email": email, "password": password, "countryCode": country_code} self._client = self._build_client(None)
@staticmethod def _build_client(access_token): headers = {"Authorization": f"Bearer {access_token}"} if access_token else {} transport = HTTPXTransport(url=API_URL, headers=headers) return Client(transport=transport, fetch_schema_from_transport=False)
def login(self) -> None: result = self._build_client(None).execute(LOGIN, variable_values=self.credentials) self._client = self._build_client(result["loginWithEmailPassword"]["accessToken"])
def request(self, query_str: str, variables: dict = None) -> dict: query = gql(query_str) try: return self._client.execute(query, variable_values=variables or {}) except TransportQueryError as error: code = (error.errors or [{}])[0].get("extensions", {}).get("code") # Token expired: there is no token refresh — sign in again and retry once if code != "Unauthorized": raise self.login() return self._client.execute(query, variable_values=variables or {})import osfrom izi_client import IZIClient
def main(): izi = IZIClient( email=os.environ["IZI_EMAIL"], password=os.environ["IZI_PASSWORD"], country_code=os.environ["IZI_COUNTRY_CODE"], ) izi.login()
club_id = os.environ["IZI_CLUB_ID"]
result = izi.request(""" query GetClub($clubId: ID!) { club(id: $clubId) { id name timezone } } """, {"clubId": club_id}) print(f"Club: {result['club']['name']}")
sessions = izi.request(""" query StartedSessions($clubId: ID!) { sessions(filters: { clubId: $clubId, statuses: [STARTED] }) { items { id actualStartAt } totalCount } } """, {"clubId": club_id})
print(f"Sessions in progress: {sessions['sessions']['totalCount']}")
if __name__ == "__main__": main()Environment Variables
Section titled “Environment Variables”Use a .env file for both examples:
IZI_API_URL=https://api.x.izi.is/graphqlIZI_EMAIL=partner@example.comIZI_PASSWORD=your_secure_passwordIZI_COUNTRY_CODE=RUIZI_CLUB_ID=8b0f8c3e-...Never store tokens or passwords in the repository code.
Related Pages
Section titled “Related Pages”- IZI API: Overview — per-contour addresses and access
- Authentication & Tokens — sign-in and token details
- API Error Codes — error format and common codes
คำถามที่พบบ่อย
Is there an official IZI SDK?
No official package. IZI API is standard GraphQL, so it works with any GraphQL library: graphql-request, Apollo Client, gql + httpx. The examples below cover the main scenarios.
What dependencies do I need for a Node.js integration?
At minimum graphql-request and graphql. For production, add a logging library such as pino or winston.
How do I pass the token in Apollo Client?
Use authLink from @apollo/client/link/context. See the Apollo Client section below.
IZI LLC (ООО «ИЗИ»), TIN 7842227686, OGRN 1257800012249, office 1, premises 3-N, lit. A, 15-17 Perekupnoy lane, Saint Petersburg, 191024, Russia, admin@izi.is · Cookie settings