Tasked with getting forums page on web app from ground app, turnd out more challengingthan it looked as i had to write pretty much everything from scratch
Asi i was a part of the web frontend team, my contributions in terms of api endpoints to the project is not plentiful, i did however introduced an endpoint to the project backend that enables users to fetch local time for their given corrdinates here's how to use it:
Base URL
All endpoints are relative to your base API URL (e.g., http://127.0.0.1:8000/ in local host case).
Returns the info related to local time of caller, if the data is not available due to excess latency -not common but happen in docker images-, then returns time of the server
URL: /api/localtime/<latitude>/<longitude>
Method: GET
Auth Required: No
Request Body: None
Response:
Success (200)
{
"latitude": 41.0267, //your latitude"longitude": 29.0125, //your longitude"timezone": "Europe/Istanbul", //your timezone"local_time": "2025-05-13T12:23:50.4535226"// local time of yours
}
full code
@api_view(['GET'])
@permission_classes([AllowAny])
def get_local_hour(request, lat, lon):
try:
lat = (float(lat) + 90)%180 - 90
lon = (float(lon)+180)%360 - 180
# Create a cache key based on coordinates (rounded to 2 decimal places for better cache hits)
cache_key = f"local_time_{round(lat, 2)}_{round(lon, 2)}"
cached_result = cache.get(cache_key)
if cached_result:
logger.debug(f"Returning cached result for {lat}, {lon}")
return Response(cached_result, status=status.HTTP_200_OK)
# Set a timeout for the external API request to prevent hanging
try:
time_res = requests.get(
f"https://timeapi.io/api/time/current/coordinate?latitude={lat}&longitude={lon}",
timeout=3 # 3 seconds timeout
)
if time_res.status_code != 200:
return Response({"error": "bad request parameters"}, status=status.HTTP_400_BAD_REQUEST)
time_data = time_res.json()
logger.debug(f"time res: {time_res.status_code} time data: {time_data}")
if 'dateTime' not in time_data:
return Response({'error': 'Could not fetch time data.'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
result = {
'latitude': lat,
'longitude': lon,
'timezone': time_data['timeZone'],
'local_time': time_data['dateTime']
}
# Cache the result for 1 hour
cache.set(cache_key, result, timeout=60) # 60 seconds = 1 minute
return Response(result, status=status.HTTP_200_OK)
except requests.Timeout:
# Get the current system time
from datetime import datetime
current_time = datetime.utcnow() + timedelta(hours=2)
result = {
'latitude': lat,
'longitude': lon,
'timezone': 'UTC+2',
'local_time': current_time.strftime('%Y-%m-%d %H:%M:%S')
}
logger.error(f"Timeout when fetching time data for {lat}, {lon}")
return Response(result, status=status.HTTP_200_OK)
except requests.RequestException as e:
logger.error(f"Request error: {str(e)}")
return Response(
{'error': 'Error connecting to time service.'},
status=status.HTTP_503_SERVICE_UNAVAILABLE
)
except ValueError as e:
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
logger.error(f"Unexpected error in get_local_hour: {str(e)}")
return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Unit Tests of The Endpoint
i tested tha api by imitating the various locations on earth, getting their responses, and also some cases with invalid call parameters, thanks to those tests, i now handle for invalid float formatting, also handling out of range values and returning right kind of error mesasages on those, for trying the tests, check out PR: https://github.com/bounswe/bounswe2025group2/pull/257