Use Cases & Tutorials
Learn how to integrate Festivo API into real-world applications with these practical tutorials.
HR & Payroll Integration
Calculate Payroll Dates Excluding Holidays
Automatically determine payroll processing dates while avoiding public and city-specific holidays:
Smart Payroll Date Calculator
1import { FestivoClient } from '@festivo-io/festivo-sdk';23 async function getNextPayrollDate(country, cityCode, currentDate) {4 const client = new FestivoClient({ apiKey: process.env.FESTIVO_API_KEY || 'YOUR_API_KEY' });5 const year = new Date(currentDate).getFullYear();6 const { holidays } = await client.getHolidays(country, year, { regions: cityCode });7 const holidayDates = new Set(holidays.map(h => h.observed));89 let nextDate = new Date(currentDate);10 nextDate.setDate(nextDate.getDate() + 1);1112 while (true) {13 const dateStr = nextDate.toISOString().split('T')[0];14 const dayOfWeek = nextDate.getDay();15 if (dayOfWeek !== 0 && dayOfWeek !== 6 && !holidayDates.has(dateStr)) {16 return nextDate;17 }18 nextDate.setDate(nextDate.getDate() + 1);19 }20 }2122 const nextPayrollDate = await getNextPayrollDate('IT', 'IT-MILAN', '2026-12-06');23 console.log(`Next payroll date: ${nextPayrollDate.toISOString().split('T')[0]}`);
Why This Matters: Paying employees on city holidays can cause bank processing delays and compliance issues. This ensures payroll runs on actual working days.
Food Delivery & Logistics
Check Restaurant Availability by City
Optimize delivery operations by checking city-specific holidays that affect restaurant and courier availability:
Restaurant Availability Checker
1import { FestivoClient } from '@festivo-io/festivo-sdk';23async function isRestaurantOperating(cityCode, country, date) {4const client = new FestivoClient({ apiKey: process.env.FESTIVO_API_KEY || 'YOUR_API_KEY' });5const year = new Date(date).getFullYear();6const { holidays } = await client.getHolidays(country, year, { regions: cityCode });78const isCityHoliday = holidays.some(h => {9 return h.observed === date && h.regions?.some(r => r.type === 'city');10});1112const dayOfWeek = new Date(date).getDay();13const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;1415return {16 operating: !isCityHoliday && !isWeekend,17 reason: isCityHoliday ? 'City holiday' : isWeekend ? 'Weekend' : 'Operating normally'18};19}2021const availability = await isRestaurantOperating('IT-MILAN', 'IT', '2026-12-07');22console.log(availability);
Real-World Impact: Food delivery platforms like Deliveroo, Glovo, Uber Eats, and Wolt use city-level holiday data to:
- Adjust delivery estimates
- Notify customers of limited availability
- Optimize courier scheduling
- Reduce failed delivery attempts
Travel & Tourism
Show Local Events to Travelers
Enhance travel apps with information about local celebrations and holidays:
Local Events Finder
1interface LocalEvent {2name: string;3name_local: string;4date: string;5type: string;6description: string;7}89async function getLocalEvents(10cityCode: string,11country: string,12startDate: string,13endDate: string14): Promise<LocalEvent[]> {15const startYear = new Date(startDate).getFullYear();16const endYear = new Date(endDate).getFullYear();1718const allEvents: LocalEvent[] = [];1920// Get holidays for each year in range21for (let year = startYear; year <= endYear; year++) {22const response = await fetch(23`https://api.getfestivo.com/v3/public-holidays/list?country=${country}®ions=${cityCode}&year=${year}&api_key=YOUR_API_KEY`24);2526 const { holidays } = await response.json();2728 // Filter to date range and city-specific events29 const events = holidays30 .filter(h => h.observed >= startDate && h.observed <= endDate)31 .filter(h => h.regions?.some(r => r.type === 'city'))32 .map(h => ({33 name: h.name,34 name_local: h.name_local,35 date: h.observed,36 type: h.type,37 description: h.description || ''38 }));3940 allEvents.push(...events);4142}4344return allEvents;45}4647// Usage: Show tourists what's happening in Rome (IT-ROME)48const romeEvents = await getLocalEvents("IT-ROME", "IT", "2026-06-01", "2026-06-30");49console.log(`Local events in Rome during your visit: ${romeEvents.length}`);50romeEvents.forEach(e => {51console.log(`${e.date}: ${e.name} (${e.name_local})`);52});
Benefits for Travel Industry:
- Show travelers authentic local celebrations
- Help visitors plan around festival dates
- Enhance cultural tourism experiences
- Provide multilingual event information
Legal & Compliance
Verify Labor Law Compliance
Ensure your workforce management system complies with regional labor laws by tracking all applicable holidays:
Compliance Checker
1def check_compliance(city_code, country, work_dates):2 """3 Verify that no work is scheduled on holidays4 Returns: (is_compliant, violations)5 """6 api_key = os.getenv('FESTIVO_API_KEY')78 # Get unique years from work dates9 years = set(datetime.fromisoformat(d).year for d in work_dates)1011 # Get all holidays for those years12 all_holidays = []13 for year in years:14 response = requests.get(15 "https://api.getfestivo.com/v3/public-holidays/list",16 params={17 "country": country,18 "regions": city_code,19 "year": year,20 "api_key": api_key21 }22 )23 all_holidays.extend(response.json()["holidays"])2425 # Build set of public holiday dates26 public_holiday_dates = {27 h["observed"] for h in all_holidays28 if h.get("public", False)29 }3031 # Check for violations32 violations = [date for date in work_dates if date in public_holiday_dates]3334 return len(violations) == 0, violations3536# Usage: Check employee schedule in Milan (IT-MILAN)3738work_schedule = ["2026-12-07", "2026-12-08", "2026-12-25"]39compliant, violations = check_compliance("IT-MILAN", "IT", work_schedule)4041if not compliant:42print(f"⚠️ Labor law violation: Work scheduled on: {violations}")43print("Action required: Reschedule or provide holiday compensation")44else:45print("✓ Schedule is compliant with local holidays")
Compliance Benefits:
- Avoid labor law penalties
- Ensure employee rights are respected
- Account for regional and city-specific holidays
- Generate audit trails for inspections
E-Commerce & Delivery Scheduling
Adjust Delivery Estimates
Automatically adjust shipping estimates based on city-level holiday calendars:
Smart Delivery Estimator
1async function getDeliveryDate(destinationCityCode, destinationCountry, orderDate, processingDays) {2const year = new Date(orderDate).getFullYear();34// Get holidays for destination city5const response = await fetch(6`https://api.getfestivo.com/v3/public-holidays/list?country=${destinationCountry}®ions=${destinationCityCode}&year=${year}&api_key=YOUR_API_KEY`7);89const { holidays } = await response.json();10const holidayDates = new Set(holidays.map(h => h.observed));1112let currentDate = new Date(orderDate);13let workingDaysAdded = 0;1415while (workingDaysAdded < processingDays) {16currentDate.setDate(currentDate.getDate() + 1);17const dateStr = currentDate.toISOString().split('T')[0];18const dayOfWeek = currentDate.getDay();1920 // Count only working days (not weekends or holidays)21 if (dayOfWeek !== 0 && dayOfWeek !== 6 && !holidayDates.has(dateStr)) {22 workingDaysAdded++;23 }2425}2627return currentDate;28}2930// Usage: E-commerce delivery to Milan (IT-MILAN)31const estimatedDelivery = await getDeliveryDate("IT-MILAN", "IT", "2026-12-04", 3);32console.log(`Estimated delivery: ${estimatedDelivery.toISOString().split('T')[0]}`);33// Automatically skips Dec 7 (Saint Ambrose Day)
E-Commerce Benefits:
- Accurate delivery promises
- Reduced customer complaints
- Better carrier coordination
- Improved customer satisfaction
Financial Services
Calculate Settlement Dates
Determine accurate settlement dates for financial transactions accounting for banking holidays:
Settlement Date Calculator
1interface SettlementResult {2settlementDate: string;3businessDays: number;4holidaysSkipped: string[];5}67async function calculateSettlementDate(8country: string,9tradeDate: string,10settlementDays: number = 2 // T+2 standard11): Promise<SettlementResult> {12const year = new Date(tradeDate).getFullYear();1314const response = await fetch(15`https://api.getfestivo.com/v3/public-holidays/list?country=${country}&year=${year}&type=bank&api_key=YOUR_API_KEY`16);1718const { holidays } = await response.json();19const bankHolidays = new Set(holidays.map(h => h.observed));20const skipped: string[] = [];2122let current = new Date(tradeDate);23let businessDaysAdded = 0;2425while (businessDaysAdded < settlementDays) {26current.setDate(current.getDate() + 1);27const dateStr = current.toISOString().split('T')[0];28const dayOfWeek = current.getDay();2930 if (dayOfWeek !== 0 && dayOfWeek !== 6 && !bankHolidays.has(dateStr)) {31 businessDaysAdded++;32 } else if (bankHolidays.has(dateStr)) {33 skipped.push(dateStr);34 }3536}3738return {39settlementDate: current.toISOString().split('T')[0],40businessDays: settlementDays,41holidaysSkipped: skipped42};43}4445// Usage: Financial transaction in UK46const settlement = await calculateSettlementDate("GB", "2026-04-02", 2);47console.log(`Settlement date: ${settlement.settlementDate}`);48console.log(`Bank holidays skipped: ${settlement.holidaysSkipped.join(', ')}`);
Financial Use Cases:
- Stock trading settlement (T+2, T+3)
- Payment processing schedules
- Contract execution dates
- Compliance with market regulations
Project Management & Scheduling
Calculate Project Deadlines
Account for holidays when calculating project timelines and milestones:
Project Timeline Calculator
1async function calculateProjectDeadline(country, cityCode, startDate, workingDays) {2const year = new Date(startDate).getFullYear();3const nextYear = year + 1;45// Get holidays for current and next year6const [currentYearHolidays, nextYearHolidays] = await Promise.all([7fetch(`https://api.getfestivo.com/v3/public-holidays/list?country=${country}®ions=${cityCode}&year=${year}&api_key=YOUR_API_KEY`).then(r => r.json()),8fetch(`https://api.getfestivo.com/v3/public-holidays/list?country=${country}®ions=${cityCode}&year=${nextYear}&api_key=YOUR_API_KEY`).then(r => r.json())9]);1011const allHolidays = [...currentYearHolidays.holidays, ...nextYearHolidays.holidays];12const publicHolidays = new Set(13allHolidays14 .filter(h => h.public)15 .map(h => h.observed)16);1718let currentDate = new Date(startDate);19let workingDaysAdded = 0;20const timeline = [];2122while (workingDaysAdded < workingDays) {23currentDate.setDate(currentDate.getDate() + 1);24const dateStr = currentDate.toISOString().split('T')[0];25const dayOfWeek = currentDate.getDay();26const isWorkingDay = dayOfWeek !== 0 && dayOfWeek !== 6 && !publicHolidays.has(dateStr);2728 timeline.push({29 date: dateStr,30 isWorkingDay,31 reason: publicHolidays.has(dateStr) ? 'Holiday' : !isWorkingDay ? 'Weekend' : 'Working day'32 });3334 if (isWorkingDay) {35 workingDaysAdded++;36 }3738}3940return {41deadline: timeline[timeline.length - 1].date,42totalDays: timeline.length,43workingDays: workingDaysAdded,44holidaysEncountered: timeline.filter(d => d.reason === 'Holiday').length45};46}4748// Usage: 20 working-day project in Milan (IT-MILAN)49const deadline = await calculateProjectDeadline("IT", "IT-MILAN", "2026-11-25", 20);50console.log(`Project deadline: ${deadline.deadline}`);51console.log(`Holidays encountered: ${deadline.holidaysEncountered}`);
Project Management Benefits:
- Accurate timeline estimation
- Realistic deadline setting
- Resource planning
- Stakeholder communication
Best Practices
Caching Strategies
Cache holiday data to improve performance and reduce API calls:
Efficient Caching Pattern
1const Redis = require('redis');2const client = Redis.createClient();34async function getHolidaysWithCache(country, regionCode, year) {5const cacheKey = `holidays:${country}:${regionCode}:${year}`;67// Try cache first8const cached = await client.get(cacheKey);9if (cached) {10return JSON.parse(cached);11}1213// Fetch from API14const response = await fetch(15`https://api.getfestivo.com/v3/public-holidays/list?country=${country}®ions=${regionCode}&year=${year}&api_key=YOUR_API_KEY`16);1718const data = await response.json();1920// Cache for 24 hours21await client.setEx(cacheKey, 86400, JSON.stringify(data.holidays));2223return data.holidays;24}2526// Usage: Cache key includes region code (IT-MILAN)27const holidays = await getHolidaysWithCache("IT", "IT-MILAN", 2026);
Rate Limit Handling
Implement exponential backoff for rate limit errors:
Rate Limit Handler
1import time23def get_holidays_with_retry(country, region_code, year, max_retries=3):4api_key = os.getenv('FESTIVO_API_KEY')5url = "https://api.getfestivo.com/v3/public-holidays/list"6params = {"country": country, "regions": region_code, "year": year, "api_key": api_key}78 for attempt in range(max_retries):9 try:10 response = requests.get(url, params=params)1112 if response.status_code == 429:13 # Rate limited - check retry-after header14 retry_after = int(response.headers.get('Retry-After', 60))15 print(f"Rate limited. Retrying after {retry_after}s...")16 time.sleep(retry_after)17 continue1819 response.raise_for_status()20 return response.json()["holidays"]2122 except requests.exceptions.RequestException as e:23 if attempt == max_retries - 1:24 raise2526 # Exponential backoff27 wait_time = 2 ** attempt28 print(f"Attempt {attempt + 1} failed. Retrying in {wait_time}s...")29 time.sleep(wait_time)3031 raise Exception("Max retries exceeded")3233# Usage: Region code format is {COUNTRY_CODE}-{CITY}3435holidays = get_holidays_with_retry("IT", "IT-MILAN", 2026)
Next Steps
- View Full API Reference - Complete endpoint documentation
- Explore Subdivisions & Cities - ISO codes and city coverage
- Check Pricing Plans - Find the right plan for your needs
- Contact Support - Get help with integration