इसे छोड़कर कंटेंट पर जाएं

IZI SDK Examples: JavaScript and Python

Опубликовано: · Обновлено: (1 месяц назад)· IZI Team

यह कंटेंट अभी तक आपकी भाषा में उपलब्ध नहीं है।

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.

Terminal window
npm install graphql-request graphql
izi-client.js
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.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(),
});

Terminal window
pip install gql[httpx] httpx
izi_client.py
import os
from gql import gql, Client
from gql.transport.exceptions import TransportQueryError
from 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 {})
main.py
import os
from 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()

Use a .env file for both examples:

Terminal window
IZI_API_URL=https://api.x.izi.is/graphql
IZI_EMAIL=partner@example.com
IZI_PASSWORD=your_secure_password
IZI_COUNTRY_CODE=RU
IZI_CLUB_ID=8b0f8c3e-...

Never store tokens or passwords in the repository code.

अक्सर पूछे जाने वाले सवाल

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.

About IZI