by Lazy Sloth
Get Holidays List from Google Calendar API
import os
import logging
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
import requests
from datetime import datetime
from typing import List
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)
app = FastAPI()
GOOGLE_CALENDAR_API_KEY = os.environ.get('GOOGLE_CALENDAR_API_KEY')
if not GOOGLE_CALENDAR_API_KEY:
raise Exception("The GOOGLE_CALENDAR_API_KEY environment variable is not set.")
def fetch_holidays(country_code: str, year: str):
url = f"https://www.googleapis.com/calendar/v3/calendars/{country_code}%23holiday%40group.v.calendar.google.com/events"
params = {
'key': GOOGLE_CALENDAR_API_KEY,
'timeMin': f'{year}-01-01T00:00:00Z',
'timeMax': f'{year}-12-31T23:59:59Z',
'singleEvents': True,
Frequently Asked Questions
How can businesses benefit from using this holiday fetching app?
The Get Holidays List from Google Calendar API app can be incredibly valuable for businesses operating internationally or serving a global customer base. By easily accessing holiday information for different countries, businesses can: - Plan marketing campaigns around local holidays - Adjust customer service schedules to accommodate different countries' holidays - Optimize inventory management and supply chain operations based on holiday-related demand fluctuations - Enhance employee scheduling for multinational teams
Can this app be integrated into existing business systems?
Yes, the Get Holidays List from Google Calendar API app is designed to be easily integrated into existing business systems. As it's built using FastAPI, it can be deployed as a microservice and accessed via HTTP requests. This allows for seamless integration with various business applications such as: - HR management systems for leave planning - E-commerce platforms for displaying shipping times and managing promotions - CRM systems for scheduling follow-ups and campaigns - Project management tools for deadline setting and resource allocation
What's the process for setting up the Google Calendar API key for this app?
To set up the Google Calendar API key for the Get Holidays List app:
How can I modify the app to return holidays for multiple countries in a single request?
To modify the Get Holidays List app to return holidays for multiple countries in a single request, you can update the endpoint to accept a list of country codes. Here's an example of how you might modify the code:
```python from typing import List
@app.get("/holidays/", response_model=Dict[str, List], summary="Get Holidays for Multiple Countries") def get_holidays_multiple(country_codes: List[str] = Query(...), year: str = Query(...)): try: datetime.strptime(year, '%Y') except ValueError: raise HTTPException(status_code=400, detail="Invalid year format. Please use 'YYYY'.")
results = {}
for country_code in country_codes:
holidays = fetch_holidays(country_code, year)
results[country_code] = holidays
return JSONResponse(content=results)
```
This modification allows users to request holidays for multiple countries in one API call, enhancing the app's flexibility and efficiency.
What are some potential applications of this holiday fetching app in the travel industry?
The Get Holidays List from Google Calendar API app has numerous applications in the travel industry: - Travel agencies can use it to create targeted holiday packages - Airlines can adjust their flight schedules and pricing based on holidays in different countries - Hotel booking platforms can display local holidays to help travelers plan their trips - Travel insurance companies can use holiday data to assess risk and adjust premiums - Tour operators can design specialized tours around specific holidays or festivals
By leveraging this app, travel businesses can enhance their services, improve customer experiences, and optimize their operations around global holiday patterns.
Created: | Last Updated:
Introduction to the Get Holidays List from Google Calendar API Template
Welcome to the Get Holidays List from Google Calendar API template! This template is designed to help you build an application that fetches holiday information for a specific country and year using the Google Calendar API. It's a great tool for developers who want to integrate holiday data into their applications without having to worry about the complexities of API integration and server setup.
Clicking Start with this Template
To begin using this template, simply click on the "Start with this Template" button. This will pre-populate the code in the Lazy Builder interface, so you won't need to copy, paste, or delete any code manually.
Initial Setup: Adding Environment Secrets
Before you can use this template, you'll need to set up an environment secret for the Google Calendar API key. Here's how to do it:
- Visit the Google Developers Console and create a new project or select an existing one.
- Enable the Google Calendar API for your project.
- Go to the "Credentials" section and create an API key.
- Copy the API key you just created.
- In the Lazy Builder interface, navigate to the Environment Secrets tab.
- Create a new secret with the key `GOOGLE_CALENDAR_API_KEY` and paste the API key you copied as the value.
Test: Pressing the Test Button
Once you have set up your environment secret, you can test the application by clicking the "Test" button. This will deploy your app and launch the Lazy CLI.
Using the App
After pressing the "Test" button, Lazy will provide you with a dedicated server link to use the API. Additionally, since this template uses FastAPI, you will also be provided with a link to the API documentation.
To fetch holidays for a specific country and year, you will use the provided server link followed by the endpoint pattern `/holidays/{country_code}/{year}`. Replace `{country_code}` with the desired country code and `{year}` with the year you want to fetch holidays for.
Here's an example of how to make a request:
GET http://your-server-link/holidays/en.usa/2023
You should expect a response similar to this:
[
{
"kind": "calendar#event",
"etag": "\"etag\"",
"id": "event_id",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=event_id",
"created": "datetime",
"updated": "datetime",
"summary": "New Year's Day",
"description": "New Year's Day is a public holiday in the USA.",
...
},
...
]
Integrating the App
If you want to integrate this holiday information into another service or frontend, you can use the server link provided by Lazy to make API requests from your application. Ensure that you handle the API responses correctly and display the holiday data as needed in your application.
For example, if you're building a calendar application, you can use the fetched holiday data to mark holidays on the calendar for users based on their country and year selection.
Remember to respect the Google Calendar API usage limits and terms of service when integrating and using the API in your application.
By following these steps, you should now have a functional application that can fetch and display holiday information from the Google Calendar API. Happy building!
Template Benefits
-
Global Business Planning: Enables companies to efficiently plan their international operations by providing easy access to holiday schedules across multiple countries, facilitating better resource allocation and project timelines.
-
Enhanced Customer Service: Allows businesses to anticipate and prepare for holiday-related changes in customer behavior or support needs, improving service quality and customer satisfaction in different markets.
-
HR and Payroll Management: Simplifies the process of managing employee leave, scheduling, and payroll adjustments for multinational companies by providing accurate holiday information for various countries.
-
Marketing Campaign Optimization: Helps marketing teams to plan and execute targeted campaigns around specific holidays in different countries, maximizing the impact of their promotional efforts.
-
Supply Chain Management: Assists in optimizing inventory management and logistics planning by accounting for holiday-related disruptions or changes in demand across different regions.