DuckDuckGo / app.py
Subham9126's picture
Update app.py
66cde78 verified
Raw
History Blame Contribute Delete
6.38 kB
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from datetime import datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import pycountry
from typing import List, Optional
app = FastAPI(
title="Country DateTime API",
description="Get current date and time for any country",
version="1.0.0"
)
# Response models
class TimezoneInfo(BaseModel):
timezone: str = Field(..., description="IANA timezone name")
datetime: str = Field(..., description="Local datetime in YYYY-MM-DD HH:MM:SS format")
utc_offset: str = Field(..., description="UTC offset (e.g., +0530)")
timezone_abbr: str = Field(..., description="Timezone abbreviation (e.g., IST)")
class CountryDateTimeResponse(BaseModel):
country: str = Field(..., description="Full country name")
alpha_2: str = Field(..., description="ISO 3166-1 alpha-2 country code")
datetime_info: List[TimezoneInfo] = Field(..., description="List of timezones with datetime")
class ErrorResponse(BaseModel):
error: str = Field(..., description="Error message")
def get_country_datetime(country_name: str) -> dict:
"""
Gets the current date and time for a given country.
Args:
country_name: The name of the country.
Returns:
A dictionary with country and datetime information.
Raises:
ValueError: If country is not found or has no timezones.
"""
# Find the country
try:
country = pycountry.countries.get(name=country_name)
if not country:
country = pycountry.countries.search_fuzzy(country_name)[0]
except (LookupError, IndexError, AttributeError):
raise ValueError(f"Country '{country_name}' not found.")
# Get timezones for the country
try:
import pytz
timezones = pytz.country_timezones.get(country.alpha_2, [])
if not timezones:
raise ValueError(f"No timezones found for country '{country_name}'.")
except Exception as e:
raise ValueError(f"Error retrieving timezones: {str(e)}")
# Get datetime for each timezone
datetime_info = []
utc_now = datetime.now(ZoneInfo("UTC"))
for tz_name in timezones:
try:
timezone = ZoneInfo(tz_name)
local_time = utc_now.astimezone(timezone)
datetime_info.append({
"timezone": tz_name,
"datetime": local_time.strftime('%Y-%m-%d %H:%M:%S'),
"utc_offset": local_time.strftime('%z'),
"timezone_abbr": local_time.strftime('%Z')
})
except ZoneInfoNotFoundError:
continue
if not datetime_info:
raise ValueError(f"Could not retrieve datetime for any timezone in '{country_name}'.")
return {
"country": country.name,
"alpha_2": country.alpha_2,
"datetime_info": datetime_info
}
@app.get("/", tags=["Info"])
async def root():
"""Root endpoint with API information."""
return {
"message": "Country DateTime API",
"endpoints": {
"GET /datetime/{country_name}": "Get datetime for a specific country",
"GET /datetime": "Get datetime for a country using query parameter",
"GET /docs": "API documentation"
}
}
@app.get(
"/datetime/{country_name}",
response_model=CountryDateTimeResponse,
responses={
200: {"description": "Successful response"},
404: {"model": ErrorResponse, "description": "Country not found"},
500: {"model": ErrorResponse, "description": "Server error"}
},
tags=["DateTime"]
)
async def get_datetime_by_path(country_name: str):
"""
Get current date and time for a country using path parameter.
- **country_name**: Name of the country (e.g., "India", "United States")
"""
try:
result = get_country_datetime(country_name)
return JSONResponse(content=result)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@app.get(
"/datetime",
response_model=CountryDateTimeResponse,
responses={
200: {"description": "Successful response"},
404: {"model": ErrorResponse, "description": "Country not found"},
500: {"model": ErrorResponse, "description": "Server error"}
},
tags=["DateTime"]
)
async def get_datetime_by_query(
country: str = Query(..., description="Name of the country", examples=["India", "United States"])
):
"""
Get current date and time for a country using query parameter.
- **country**: Name of the country (e.g., "India", "United States")
"""
try:
result = get_country_datetime(country)
return JSONResponse(content=result)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@app.get("/countries", tags=["Info"])
async def list_countries(
search: Optional[str] = Query(None, description="Search term to filter countries")
):
"""
List all available countries or search for specific countries.
- **search**: Optional search term to filter countries
"""
countries = []
for country in pycountry.countries:
if search:
if search.lower() in country.name.lower():
countries.append({
"name": country.name,
"alpha_2": country.alpha_2,
"alpha_3": country.alpha_3
})
else:
countries.append({
"name": country.name,
"alpha_2": country.alpha_2,
"alpha_3": country.alpha_3
})
return {
"total": len(countries),
"countries": countries[:100] if not search else countries
}
@app.get("/health", tags=["Info"])
async def health_check():
"""Health check endpoint."""
return {
"status": "healthy",
"timestamp": datetime.now(ZoneInfo("UTC")).isoformat()
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)