Chuyển tới nội dung chính

Code Examples

Ví dụ code chi tiết để tích hợp với External API.

Python Example​

Setup API Client​

import json
import requests
from typing import Optional, Dict, Any, List

class CohostClient:
def __init__(self, api_key: str, base_url: str = "https://api.cohost.vn"):
self.api_key = api_key
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
"X-API-Key": api_key,
"Content-Type": "application/json"
})

def _request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
url = f"{self.base_url}{endpoint}"
response = self.session.request(method, url, **kwargs)
response.raise_for_status()
return response.json()

# Listings
def list_listings(self, page: int = 1, limit: int = 20, team_ids: Optional[List[int]] = None,
state: Optional[str] = None, country_code: Optional[str] = None,
province_code: Optional[str] = None) -> Dict[str, Any]:
params = {"page": page, "limit": limit}
if team_ids:
params["team_ids"] = json.dumps(team_ids)
if state:
params["state"] = state
if country_code:
params["country_code"] = country_code
if province_code:
params["province_code"] = province_code
return self._request("GET", "/api/v1/external/listings", params=params)

def get_listing(self, listing_id: str) -> Dict[str, Any]:
return self._request("GET", f"/api/v1/external/listings/{listing_id}")

def get_availability(self, listing_id: str, start_date: str, end_date: str) -> Dict[str, Any]:
return self._request(
"GET",
f"/api/v1/external/listings/{listing_id}/availability",
params={"start_date": start_date, "end_date": end_date}
)

# Bookings
def list_bookings(self, page: int = 1, limit: int = 20, team_ids: Optional[List[int]] = None,
user_id: Optional[int] = None, state: Optional[str] = None) -> Dict[str, Any]:
params = {"page": page, "limit": limit}
if team_ids:
params["team_ids"] = json.dumps(team_ids)
if user_id:
params["user_id"] = user_id
if state:
params["state"] = state
return self._request("GET", "/api/v1/external/bookings", params=params)

def get_booking(self, booking_id: str) -> Dict[str, Any]:
return self._request("GET", f"/api/v1/external/bookings/{booking_id}")

def create_booking(self, listing_id: str, check_in: str, check_out: str,
guests: int, guest_info: Dict[str, str]) -> Dict[str, Any]:
data = {
"listing_id": listing_id,
"check_in": check_in,
"check_out": check_out,
"guests": guests,
"guest_info": guest_info
}
return self._request("POST", "/api/v1/external/bookings", json=data)

Sử dụng Client​

# Initialize client
client = CohostClient(api_key="ck_live_xxxxxxxxxxxx")

# Lấy danh sách listings từ tất cả teams
listings = client.list_listings(page=1, limit=20)
for listing in listings:
print(f"- {listing['name']} ({listing['id']})")

# Lấy listings từ teams cụ thể
listings_filtered = client.list_listings(page=1, limit=20, team_ids=[1, 2, 3])

# Kiểm tra availability
availability = client.get_availability(
listing_id="uuid-cua-listing",
start_date="2025-03-01",
end_date="2025-03-07"
)
print(availability)

# Tạo booking (team_id được tự động lấy từ listing_id)
booking = client.create_booking(
listing_id=123,
check_in_date="2025-03-01",
check_out_date="2025-03-05",
guest_number=2,
guest_info={
"full_name": "Nguyen Van A",
"phone": "+84901234567",
"email": "guest@example.com"
}
)
print(f"Created booking: {booking['id']}")

# Lấy bookings từ tất cả teams
bookings = client.list_bookings(page=1, limit=20)

# Lấy bookings của customer cụ thể
customer_bookings = client.list_bookings(page=1, limit=20, user_id=200)

# Lấy bookings từ teams cụ thể với filter state
confirmed_bookings = client.list_bookings(page=1, limit=20, team_ids=[1, 2], state="CONFIRMED")

Node.js Example​

const axios = require('axios');

class CohostClient {
constructor(apiKey, options = {}) {
this.apiKey = apiKey;
this.baseUrl = options.baseUrl || 'https://api.cohost.vn';

this.client = axios.create({
baseURL: this.baseUrl,
headers: {
'X-API-Key': this.apiKey,
'Content-Type': 'application/json'
}
});
}

async listListings(page = 1, limit = 20, teamIds = null, state = null,
countryCode = null, provinceCode = null) {
const params = { page, limit };
if (teamIds) {
params.team_ids = JSON.stringify(teamIds);
}
if (state) params.state = state;
if (countryCode) params.country_code = countryCode;
if (provinceCode) params.province_code = provinceCode;

const response = await this.client.get('/api/v1/external/listings', { params });
return response.data;
}

async getListing(listingId) {
const response = await this.client.get(`/api/v1/external/listings/${listingId}`);
return response.data;
}

async getAvailability(listingId, startDate, endDate) {
const response = await this.client.get(
`/api/v1/external/listings/${listingId}/availability`,
{ params: { start_date: startDate, end_date: endDate } }
);
return response.data;
}

async listBookings(page = 1, limit = 20, teamIds = null, userId = null, state = null) {
const params = { page, limit };
if (teamIds) {
params.team_ids = JSON.stringify(teamIds);
}
if (userId) params.user_id = userId;
if (state) params.state = state;

const response = await this.client.get('/api/v1/external/bookings', { params });
return response.data;
}

async createBooking(data) {
const response = await this.client.post('/api/v1/external/bookings', data);
return response.data;
}
}

// Sử dụng
const client = new CohostClient('ck_live_xxxxxxxxxxxx');

// Lấy listings từ tất cả teams
const listings = await client.listListings(1, 20);
console.log(listings);

// Lấy listings từ teams cụ thể
const filteredListings = await client.listListings(1, 20, [1, 2, 3]);
console.log(filteredListings);

// Lấy bookings từ tất cả teams
const bookings = await client.listBookings(1, 20);
console.log(bookings);

// Lấy bookings của customer cụ thể
const customerBookings = await client.listBookings(1, 20, null, 200);
console.log(customerBookings);

// Tạo booking (team_id được tự động lấy từ listing_id)
const booking = await client.createBooking({
listing_id: 123,
check_in_date: '2025-03-01',
check_out_date: '2025-03-05',
guest_number: 2,
guest_info: {
full_name: 'Nguyen Van A',
phone: '+84901234567',
email: 'guest@example.com'
}
});
console.log(booking);

Error Handling Example​

import requests
from requests.exceptions import HTTPError

def safe_api_call(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except HTTPError as e:
if e.response.status_code == 429:
# Rate limited - wait and retry
import time
reset_time = int(e.response.headers.get('X-RateLimit-Reset', 0))
wait_time = max(0, reset_time - time.time())
time.sleep(wait_time + 1) # +1 buffer
return func(*args, **kwargs)
elif e.response.status_code == 404:
print(f"Resource not found: {e.response.json()}")
return None
else:
print(f"API Error: {e.response.json()}")
raise
return wrapper

# Usage
@safe_api_call
def get_listing_safe(client, listing_id):
return client.get_listing(listing_id)