Python SDK for Singapore Government Data APIs
Project description
SGData SDK (Python)
Python client for Singapore Government Data APIs. A unified SDK providing access to weather, air quality, and carpark availability data from data.gov.sg.
This is the Python version of sgdata-sdk (TypeScript).
Features
- Single Unified Client: One client class for all 9 core endpoints
- Full Type Hints: Complete type annotations for better IDE support
- Optional Historical Data: Access current or historical data with optional parameters
- Simple API: Clean, intuitive interface following Python best practices
- Zero Configuration: Works out of the box with sensible defaults
Installation
pip install sgdata-sdk
Quick Start
from sgdata import SGDataClient
# Initialize the client
client = SGDataClient()
# Get current PSI readings
psi_data = client.get_psi()
print(psi_data)
# Get historical PSI data
historical_psi = client.get_psi(date_time="2024-01-15T12:00:00")
# Use as context manager (auto-closes session)
with SGDataClient() as client:
weather = client.get_2hour_weather_forecast()
rainfall = client.get_rainfall()
Available Endpoints
Air Quality
get_psi()- Pollutant Standards Indexget_pm25()- PM2.5 readings
Weather Forecasts
get_2hour_weather_forecast()- Short-term forecastget_24hour_weather_forecast()- Daily forecastget_4day_weather_forecast()- Extended forecast
Weather Measurements
get_rainfall()- Rainfall measurementsget_relative_humidity()- Humidity readingsget_air_temperature()- Temperature readings
Transport
get_carpark_availability()- HDB carpark availability
Usage Examples
Current Data
from sgdata import SGDataClient
client = SGDataClient()
# Get current air quality
psi = client.get_psi()
pm25 = client.get_pm25()
# Get current weather
forecast_2h = client.get_2hour_weather_forecast()
forecast_24h = client.get_24hour_weather_forecast()
forecast_4d = client.get_4day_weather_forecast()
# Get current measurements
rainfall = client.get_rainfall()
humidity = client.get_relative_humidity()
temperature = client.get_air_temperature()
# Get carpark availability
carparks = client.get_carpark_availability()
Historical Data
All endpoints (except carpark availability) support both date_time and date parameters:
# Using date_time (ISO 8601 format)
psi = client.get_psi(date_time="2024-01-15T12:00:00")
# Using date (YYYY-MM-DD format)
psi = client.get_psi(date="2024-01-15")
# Carpark availability only supports date_time
carparks = client.get_carpark_availability(date_time="2024-01-15T12:00:00")
Error Handling
import requests
from sgdata import SGDataClient
client = SGDataClient()
try:
data = client.get_psi()
except requests.HTTPError as e:
print(f"HTTP error: {e}")
except requests.RequestException as e:
print(f"Request failed: {e}")
Custom Configuration
# Custom base URL and timeout
client = SGDataClient(
base_url="https://custom-api.example.com/v1",
timeout=60
)
# Access the requests session for advanced configuration
client.session.headers.update({"Custom-Header": "value"})
API Reference
SGDataClient
__init__(base_url: Optional[str] = None, timeout: int = 30)
Initialize the client.
Parameters:
base_url: Custom API base URL (default:https://api.data.gov.sg/v1)timeout: Request timeout in seconds (default: 30)
Endpoint Methods
All endpoint methods follow this pattern:
def get_endpoint_name(
self,
date_time: Optional[str] = None,
date: Optional[str] = None
) -> Dict[str, Any]:
"""Endpoint description."""
Parameters:
date_time: ISO 8601 datetime string (e.g., "2024-01-15T12:00:00")date: Date string in YYYY-MM-DD format (e.g., "2024-01-15")
Returns:
Dict[str, Any]: Parsed JSON response from the API
Raises:
requests.HTTPError: If the request fails (4xx, 5xx status codes)requests.RequestException: For other request-related errors
Development
Setup
# Clone the repository
git clone https://github.com/KT-afk/sgdata-sdk-python.git
cd sgdata-sdk-python
# Install in development mode with dev dependencies
pip install -e ".[dev]"
Running Tests
pytest
Type Checking
mypy sgdata
Code Formatting
# Format code
black sgdata tests
# Lint code
ruff check sgdata tests
Design Decisions
Why a Single Client?
Unlike the existing datagovsg package which has 4 separate clients, this SDK uses a single unified SGDataClient class. This approach:
- Simplifies the API surface
- Reduces import complexity
- Makes it easier to discover available endpoints
- Follows the principle of cohesion (all endpoints are related to SG government data)
Why Optional Parameters Instead of Separate Methods?
Instead of having separate methods like get_psi() and get_historical_psi(date), we use optional parameters:
- Cleaner API with fewer methods to learn
- More intuitive - "get PSI data, optionally at this time"
- Consistent pattern across all endpoints
- Aligns with the TypeScript SDK design
Why Not **kwargs?
We use explicit date_time and date parameters instead of **kwargs for:
- Better IDE autocomplete and type checking
- Clear documentation of available parameters
- Prevention of typos (e.g.,
datetimevsdate_time) - Explicit is better than implicit (Zen of Python)
License
MIT License - see LICENSE file for details.
Related Projects
- sgdata-sdk - TypeScript version
- data.gov.sg - Official Singapore Government Data Portal
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sgdata_sdk-0.1.0.tar.gz.
File metadata
- Download URL: sgdata_sdk-0.1.0.tar.gz
- Upload date:
- Size: 8.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
294f7ae6b8da63cb74b5e0d5697cf78887d7436b9ecd74d3c23ff42856de7774
|
|
| MD5 |
9f1f527772dd42cf05176d69ff3261ec
|
|
| BLAKE2b-256 |
cf140ad8620656f9ee81b59daaea0e50e3b636f68397c0f4c237c109ffa11763
|
File details
Details for the file sgdata_sdk-0.1.0-py3-none-any.whl.
File metadata
- Download URL: sgdata_sdk-0.1.0-py3-none-any.whl
- Upload date:
- Size: 6.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8b9b3764ef11838def0a07c6b9dc80aba88b790fbad9f7542f7b8d5aef43df2b
|
|
| MD5 |
e43b26e9b15d442268542ee051f4b65d
|
|
| BLAKE2b-256 |
7f551315714da9b5c3b59ee6eb745e2f264ea672bff840f8e9d729ffbd49388d
|