Примеры интеграции
Готовые сценарии и примеры кода на разных языках
Примеры интеграции
Готовые сценарии использования API на разных языках программирования.
Сценарий 1: Поиск и отображение игр
Поиск игр по запросу пользователя и отображение результатов с ценами.
async function searchGames(query, platform = 'all') {
const apiKey = 'gapi_xxxxxxxxxxxxxxxxxxxxx';
try {
const response = await fetch(
`https://gapi.qb2.ru/api/v1/catalog/search?` + new URLSearchParams({
q: query,
platform: platform,
limit: 10,
includeRelated: 1
}),
{
headers: {
'Authorization': `Bearer ${apiKey}`
}
}
);
const data = await response.json();
if (!data.ok) {
throw new Error(data.error.message);
}
// Отображение результатов
data.data.results.forEach(game => {
console.log(`${game.title} - ${game.price.formatted}`);
console.log(`Platform: ${game.platform}`);
console.log(`Store: ${game.storeUrl}`);
console.log('---');
});
// Проверка лимитов
const remaining = response.headers.get('X-RateLimit-Remaining-Minute');
console.log(`Осталось запросов: ${remaining}`);
return data.data.results;
} catch (error) {
console.error('Ошибка поиска:', error.message);
throw error;
}
}
// Использование
searchGames('god of war', 'psn');import requests
def search_games(query, platform='all'):
api_key = 'gapi_xxxxxxxxxxxxxxxxxxxxx'
try:
response = requests.get(
'https://gapi.qb2.ru/api/v1/catalog/search',
params={
'q': query,
'platform': platform,
'limit': 10,
'includeRelated': 1
},
headers={'Authorization': f'Bearer {api_key}'}
)
data = response.json()
if not data['ok']:
raise Exception(data['error']['message'])
# Отображение результатов
for game in data['data']['results']:
print(f"{game['title']} - {game['price']['formatted']}")
print(f"Platform: {game['platform']}")
print(f"Store: {game['storeUrl']}")
print('---')
# Проверка лимитов
remaining = response.headers.get('X-RateLimit-Remaining-Minute')
print(f"Осталось запросов: {remaining}")
return data['data']['results']
except Exception as e:
print(f"Ошибка поиска: {e}")
raise
# Использование
search_games('god of war', 'psn')<?php
function searchGames($query, $platform = 'all') {
$apiKey = 'gapi_xxxxxxxxxxxxxxxxxxxxx';
$url = 'https://gapi.qb2.ru/api/v1/catalog/search?' . http_build_query([
'q' => $query,
'platform' => $platform,
'limit' => 10,
'includeRelated' => 1
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey
]);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
$data = json_decode($body, true);
if (!$data['ok']) {
throw new Exception($data['error']['message']);
}
// Отображение результатов
foreach ($data['data']['results'] as $game) {
echo $game['title'] . ' - ' . $game['price']['formatted'] . "\n";
echo 'Platform: ' . $game['platform'] . "\n";
echo 'Store: ' . $game['storeUrl'] . "\n";
echo "---\n";
}
// Проверка лимитов
preg_match('/X-RateLimit-Remaining-Minute: (\d+)/', $headers, $matches);
if (isset($matches[1])) {
echo "Осталось запросов: " . $matches[1] . "\n";
}
return $data['data']['results'];
}
// Использование
searchGames('god of war', 'psn');
?>using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
class GameSearcher
{
private static readonly HttpClient client = new HttpClient();
private const string apiKey = "gapi_xxxxxxxxxxxxxxxxxxxxx";
static async Task<JsonDocument> SearchGames(string query, string platform = "all")
{
var url = $"https://gapi.qb2.ru/api/v1/catalog/search?" +
$"q={Uri.EscapeDataString(query)}&" +
$"platform={platform}&limit=10&includeRelated=1";
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
var data = JsonDocument.Parse(content);
if (!data.RootElement.GetProperty("ok").GetBoolean())
{
var errorMsg = data.RootElement.GetProperty("error")
.GetProperty("message").GetString();
throw new Exception(errorMsg);
}
// Отображение результатов
var results = data.RootElement.GetProperty("data")
.GetProperty("results");
foreach (var game in results.EnumerateArray())
{
var title = game.GetProperty("title").GetString();
var price = game.GetProperty("price")
.GetProperty("formatted").GetString();
var gamePlatform = game.GetProperty("platform").GetString();
var storeUrl = game.GetProperty("storeUrl").GetString();
Console.WriteLine($"{title} - {price}");
Console.WriteLine($"Platform: {gamePlatform}");
Console.WriteLine($"Store: {storeUrl}");
Console.WriteLine("---");
}
// Проверка лимитов
if (response.Headers.TryGetValues("X-RateLimit-Remaining-Minute",
out var values))
{
Console.WriteLine($"Осталось запросов: {values.First()}");
}
return data;
}
static async Task Main()
{
await SearchGames("god of war", "psn");
}
}Сценарий 2: Получение детальной информации
Получение полной карточки игры с ценами и связанным контентом.
async function getGameDetails(gameId) {
const apiKey = 'gapi_xxxxxxxxxxxxxxxxxxxxx';
const response = await fetch(
`https://gapi.qb2.ru/api/v1/catalog/games/${gameId}`,
{
headers: {
'Authorization': `Bearer ${apiKey}`
}
}
);
const data = await response.json();
if (!data.ok) {
throw new Error(data.error.message);
}
const game = data.data;
console.log(`Название: ${game.title}`);
console.log(`Цена: ${game.price.formatted}`);
console.log(`Издатель: ${game.publisher}`);
console.log(`Дата выхода: ${game.releaseDate}`);
console.log(`Жанры: ${game.genres.join(', ')}`);
// Скидка
if (game.price.discount) {
console.log(`Скидка: ${game.price.discount.percentage}%`);
console.log(`До: ${game.price.discount.endsAt}`);
}
// Связанный контент
if (game.related && game.related.length > 0) {
console.log('\nDLC и дополнения:');
game.related.forEach(item => {
console.log(`- ${item.title} (${item.price.formatted})`);
});
}
// Варианты изданий
if (game.variants && game.variants.length > 0) {
console.log('\nДругие издания:');
game.variants.forEach(variant => {
console.log(`- ${variant.title} (${variant.price.formatted})`);
});
}
return game;
}
// Использование
getGameDetails('6754AQWE');import requests
from datetime import datetime
def get_game_details(game_id):
api_key = 'gapi_xxxxxxxxxxxxxxxxxxxxx'
response = requests.get(
f'https://gapi.qb2.ru/api/v1/catalog/games/{game_id}',
headers={'Authorization': f'Bearer {api_key}'}
)
data = response.json()
if not data['ok']:
raise Exception(data['error']['message'])
game = data['data']
print(f"Название: {game['title']}")
print(f"Цена: {game['price']['formatted']}")
print(f"Издатель: {game['publisher']}")
print(f"Дата выхода: {game['releaseDate']}")
print(f"Жанры: {', '.join(game['genres'])}")
# Скидка
if 'discount' in game['price']:
discount = game['price']['discount']
print(f"Скидка: {discount['percentage']}%")
print(f"До: {discount['endsAt']}")
# Связанный контент
if game.get('related'):
print('\nDLC и дополнения:')
for item in game['related']:
print(f"- {item['title']} ({item['price']['formatted']})")
# Варианты изданий
if game.get('variants'):
print('\nДругие издания:')
for variant in game['variants']:
print(f"- {variant['title']} ({variant['price']['formatted']})")
return game
# Использование
get_game_details('6754AQWE')Сценарий 3: Мониторинг цен со скидками
Отслеживание игр со скидками и уведомления.
async function findDiscountedGames(searchQuery) {
const apiKey = 'gapi_xxxxxxxxxxxxxxxxxxxxx';
// Поиск игр
const searchResponse = await fetch(
`https://gapi.qb2.ru/api/v1/catalog/search?q=${encodeURIComponent(searchQuery)}&limit=20`,
{
headers: { 'Authorization': `Bearer ${apiKey}` }
}
);
const searchData = await searchResponse.json();
const discountedGames = [];
// Проверка каждой игры на скидки
for (const game of searchData.data.results) {
const detailsResponse = await fetch(
`https://gapi.qb2.ru/api/v1/catalog/games/${game.id}`,
{
headers: { 'Authorization': `Bearer ${apiKey}` }
}
);
const details = await detailsResponse.json();
if (details.data.price.discount) {
discountedGames.push({
title: details.data.title,
originalPrice: details.data.price.discount.originalPrice,
currentPrice: details.data.price.value,
discount: details.data.price.discount.percentage,
endsAt: details.data.price.discount.endsAt,
url: details.data.storeUrl
});
}
// Задержка для соблюдения rate limit
await new Promise(resolve => setTimeout(resolve, 2000));
}
// Вывод результатов
console.log(`Найдено игр со скидками: ${discountedGames.length}`);
discountedGames.forEach(game => {
console.log(`\n${game.title}`);
console.log(`Скидка: ${game.discount}%`);
console.log(`Было: ${game.originalPrice / 100} ₽`);
console.log(`Стало: ${game.currentPrice / 100} ₽`);
console.log(`До: ${new Date(game.endsAt).toLocaleDateString()}`);
console.log(`Ссылка: ${game.url}`);
});
return discountedGames;
}
// Использование
findDiscountedGames('action games');Сценарий 4: Сравнение цен между платформами
Поиск игры на разных платформах и сравнение цен.
async function comparePrices(gameName) {
const apiKey = 'gapi_xxxxxxxxxxxxxxxxxxxxx';
const platforms = ['psn', 'battlenet'];
const results = {};
for (const platform of platforms) {
const response = await fetch(
`https://gapi.qb2.ru/api/v1/catalog/search?` + new URLSearchParams({
q: gameName,
platform: platform,
limit: 1
}),
{
headers: { 'Authorization': `Bearer ${apiKey}` }
}
);
const data = await response.json();
if (data.data.results.length > 0) {
const game = data.data.results[0];
results[platform] = {
title: game.title,
price: game.price.value,
formatted: game.price.formatted,
url: game.storeUrl
};
}
}
// Сравнение
console.log(`Сравнение цен для "${gameName}":\n`);
for (const [platform, info] of Object.entries(results)) {
console.log(`${platform.toUpperCase()}: ${info.formatted}`);
console.log(`Ссылка: ${info.url}\n`);
}
// Определение лучшей цены
const cheapest = Object.entries(results)
.sort((a, b) => a[1].price - b[1].price)[0];
if (cheapest) {
console.log(`Лучшая цена: ${cheapest[0].toUpperCase()} - ${cheapest[1].formatted}`);
}
return results;
}
// Использование
comparePrices('Diablo IV');Сценарий 5: Автодополнение для поиска
Реализация автодополнения в реальном времени.
class GameAutocomplete {
constructor(apiKey) {
this.apiKey = apiKey;
this.cache = new Map();
this.debounceTimer = null;
}
async suggest(query, callback) {
// Debounce
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(async () => {
// Проверка кэша
if (this.cache.has(query)) {
callback(this.cache.get(query));
return;
}
try {
const response = await fetch(
`https://gapi.qb2.ru/api/v1/catalog/suggest?q=${encodeURIComponent(query)}&limit=8`,
{
headers: { 'Authorization': `Bearer ${this.apiKey}` }
}
);
const data = await response.json();
if (data.ok) {
const suggestions = data.data.suggestions.map(game => ({
id: game.id,
title: game.title,
platform: game.platform,
thumbnail: game.thumbnail
}));
// Сохранение в кэш
this.cache.set(query, suggestions);
callback(suggestions);
}
} catch (error) {
console.error('Ошибка автодополнения:', error);
callback([]);
}
}, 300); // Задержка 300ms
}
}
// Использование
const autocomplete = new GameAutocomplete('gapi_xxxxxxxxxxxxxxxxxxxxx');
// В обработчике input
document.querySelector('#search-input').addEventListener('input', (e) => {
const query = e.target.value;
if (query.length < 2) {
return;
}
autocomplete.suggest(query, (suggestions) => {
// Отображение подсказок
console.log('Подсказки:', suggestions);
});
});Все примеры включают базовую обработку ошибок. В production добавьте retry logic и более детальную обработку rate limiting.
Готовые рецепты
Поиск игр
curl -H "Authorization: Bearer gapi_..." \
"https://gapi.qb2.ru/api/v1/catalog/search?q=ufc%205&platform=psn&limit=5&includeRelated=1"Карточка игры
curl -H "Authorization: Bearer gapi_..." \
"https://gapi.qb2.ru/api/v1/catalog/games/6754AQWE"Текущий usage
curl -H "Authorization: Bearer gapi_..." \
"https://gapi.qb2.ru/api/v1/account/usage"Курсы валют
curl -H "Authorization: Bearer gapi_..." \
"https://gapi.qb2.ru/api/v1/catalog/exchange-rates"