---
updatedAt: 2025-09-17T00:21:42.000Z
agentTools:
  projectIndex: https://booking-api-docs.guesty.com/llms.txt
---

# Access token management

```node Node
/**
 * Guesty Booking Engine API Token Management Example
 *
 * This Node.js script demonstrates how to:
 * - Request an access token using client credentials
 * - Cache the token locally to avoid unnecessary renewals
 * - Reuse the token in subsequent API requests
 * - Refresh the token 5 minutes before it expires
 *
 * Prerequisites:
 * - Node.js installed
 * - Your Guesty API Client ID and Client Secret
 */

const axios = require('axios');
const fs = require('fs');
const path = require('path');

// === Configuration ===
const TOKEN_FILE = path.join(__dirname, 'guesty-token.json'); // Where the token will be cached
const CLIENT_ID = 'YOUR_CLIENT_ID';       // Replace with your Guesty application client ID
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET'; // Replace with your Guesty application client secret
const TOKEN_URL = 'https://booking.guesty.com/oauth2/token';  // Token request endpoint

/**
 * Checks if a valid token is cached. If so, returns it.
 * Otherwise, calls the function to request a new token.
 */
async function getCachedToken() {
  if (fs.existsSync(TOKEN_FILE)) {
    const { access_token, expires_at } = JSON.parse(fs.readFileSync(TOKEN_FILE));
    if (Date.now() < expires_at) {
      return access_token; // Token still valid
    }
  }
  return await requestNewToken(); // Token expired or missing
}

/**
 * Requests a new token from the Guesty API and caches it with an expiration timestamp.
 */
async function requestNewToken() {
  const params = new URLSearchParams();
  params.append('grant_type', 'client_credentials');
  params.append('scope', 'booking_engine:api');
  params.append('client_id', CLIENT_ID);
  params.append('client_secret', CLIENT_SECRET);

  const response = await axios.post(TOKEN_URL, params, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  });

  const { access_token, expires_in } = response.data;

  // Set expiration to 5 minutes before actual expiry
  const expires_at = Date.now() + (expires_in - 300) * 1000;

  fs.writeFileSync(TOKEN_FILE, JSON.stringify({ access_token, expires_at }));
  return access_token;
}

/**
 * Demonstrates how to use the access token in an authenticated request to the Booking API.
 */
async function makeAuthorizedRequest() {
  const token = await getCachedToken();

  const response = await axios.get('https://booking-api.guesty.com/v1/search', {
    headers: {
      'Authorization': `Bearer ${token}`,
      'accept': 'application/json; charset=utf-8'
    },
    params: {
      checkIn: '2025-07-01',
      checkOut: '2025-07-05',
      adults: 2
    }
  });

  console.log('Search results:', response.data);
}

makeAuthorizedRequest();

```

```python Python
"""
This script demonstrates how to manage a Guesty Booking Engine API access token in Python.
It caches the token to avoid exceeding issuance limits and refreshes it before it expires.
"""

import time
import json
import os
import requests

TOKEN_FILE = 'guesty_token.json'
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
TOKEN_URL = 'https://booking.guesty.com/oauth2/token'

def get_cached_token():
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE, 'r') as f:
            data = json.load(f)
            if time.time() < data['expires_at']:
                return data['access_token']
    return request_new_token()

def request_new_token():
    payload = {
        'grant_type': 'client_credentials',
        'scope': 'booking_engine:api',
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET
    }

    response = requests.post(TOKEN_URL, data=payload)
    response.raise_for_status()
    token_data = response.json()

    # Refresh 5 minutes before expiry
    expires_at = time.time() + (token_data['expires_in'] - 300)
    with open(TOKEN_FILE, 'w') as f:
        json.dump({'access_token': token_data['access_token'], 'expires_at': expires_at}, f)

    return token_data['access_token']

def make_authenticated_request():
    token = get_cached_token()
    headers = {
        'Authorization': f'Bearer {token}',
        'accept': 'application/json; charset=utf-8'
    }
    params = {
        'checkIn': '2025-07-01',
        'checkOut': '2025-07-05',
        'adults': 2
    }

    response = requests.get('https://booking-api.guesty.com/v1/search', headers=headers, params=params)
    print(response.json())

make_authenticated_request()

```

```php PHP
<?php
/**
 * This script demonstrates how to generate and reuse a Guesty Booking Engine API token in PHP.
 * It stores the token locally and refreshes it 5 minutes before expiration.
 */

define('TOKEN_FILE', __DIR__ . '/guesty_token.json');
define('CLIENT_ID', 'YOUR_CLIENT_ID');
define('CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
define('TOKEN_URL', 'https://booking.guesty.com/oauth2/token');

function get_cached_token() {
    if (file_exists(TOKEN_FILE)) {
        $data = json_decode(file_get_contents(TOKEN_FILE), true);
        if (time() < $data['expires_at']) {
            return $data['access_token'];
        }
    }
    return request_new_token();
}

function request_new_token() {
    $post_fields = http_build_query([
        'grant_type' => 'client_credentials',
        'scope' => 'booking_engine:api',
        'client_id' => CLIENT_ID,
        'client_secret' => CLIENT_SECRET
    ]);

    $ch = curl_init(TOKEN_URL);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_POSTFIELDS => $post_fields
    ]);

    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);

    $data['expires_at'] = time() + $data['expires_in'] - 300; // 5 min buffer
    file_put_contents(TOKEN_FILE, json_encode($data));

    return $data['access_token'];
}

function make_authenticated_request() {
    $token = get_cached_token();
    $ch = curl_init('https://booking-api.guesty.com/v1/search?checkIn=2025-07-01&checkOut=2025-07-05&adults=2');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $token,
            'accept: application/json; charset=utf-8'
        ]
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    echo $response;
}

make_authenticated_request();
?>

```

```json Response Example
{"success":true}
```

# Check for valid token

<!-- node@26-37 -->
<!-- python@6-22 -->
<!-- php@7-20 -->

Check if a valid token is cached

# Generate new token

<!-- node@39-60 -->
<!-- python@24-41 -->
<!-- php@22-46 -->

If the existing token has expired, create a new one. Note the expiration logic to help prevent uninterrupted API access.

# Test the access token

<!-- node@62-81 -->
<!-- python@43-58 -->
<!-- php@48-64 -->

Test the validity of the access token by making an API request.