Skip to content

Commit 7560b0a

Browse files
Merge pull request #30 from OneBusAway/examples
Examples
2 parents 7ec9ba0 + 5a63a9d commit 7560b0a

26 files changed

Lines changed: 464 additions & 94 deletions

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
# Onebusaway SDK Python API library
1+
# OneBusAway SDK Python API library
22

33
[![PyPI version](https://img.shields.io/pypi/v/onebusaway.svg)](https://pypi.org/project/onebusaway/)
44

5-
The Onebusaway SDK Python library provides convenient access to the Onebusaway SDK REST API from any Python 3.7+
5+
The OneBusAway SDK Python library provides convenient access to the OneBusAway SDK REST API from any Python 3.7+
66
application. The library includes type definitions for all request params and response fields,
77
and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).
88

examples/.env.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
api_key="TEST"
2+
base_url="https://api.pugetsound.onebusaway.org/"

examples/README.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Examples README
2+
3+
## Setting up the environment
4+
5+
### With Rye
6+
7+
We use [Rye](https://rye.astral.sh/) to manage dependencies so we highly recommend [installing it](https://rye.astral.sh/guide/installation/) as it will automatically provision a Python environment with the expected Python version.
8+
9+
After installing Rye, you'll just have to run this command:
10+
11+
```sh
12+
$ rye sync --all-features
13+
```
14+
15+
You can then run scripts using `rye run python script.py` or by activating the virtual environment:
16+
17+
```sh
18+
$ rye shell
19+
# or manually activate - https://docs.python.org/3/library/venv.html#how-venvs-work
20+
$ source .venv/bin/activate
21+
22+
# now you can omit the `rye run` prefix
23+
$ python script.py
24+
```
25+
26+
### Without Rye
27+
28+
Alternatively if you don't want to install `Rye`, you can stick with the standard `pip` setup by ensuring you have the Python version specified in `.python-version`, create a virtual environment however you desire and then install dependencies using this command:
29+
30+
```sh
31+
$ pip install -r requirements-dev.lock
32+
```
33+
34+
## Run the examples
35+
36+
```bash
37+
python EXAMPLE_NAME.py
38+
```
39+
40+
## `.env` file: API keys and server URLs
41+
42+
Copy the file `.env.example` to `.env` and edit it with your preferred API key and server URL.

examples/agencies_with_coverage.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from pprint import pprint
2+
3+
from helpers.load_env import load_settings
4+
5+
from onebusaway import OnebusawaySDK
6+
7+
# Load settings from .env file, if it exists. If not, we'll use the
8+
# Puget Sound server URL (which is also the default in the SDK) and
9+
# the 'TEST' API key.
10+
settings = load_settings(
11+
{
12+
"api_key": "TEST",
13+
"base_url": "https://api.pugetsound.onebusaway.org/",
14+
}
15+
)
16+
17+
# Create a new instance of the OneBusAway SDK with the settings we loaded.
18+
oba = OnebusawaySDK(**settings)
19+
20+
response = oba.agencies_with_coverage.retrieve()
21+
pprint(response.data)

examples/agency.py

Lines changed: 0 additions & 15 deletions
This file was deleted.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from helpers.load_env import load_settings
2+
3+
from onebusaway import OnebusawaySDK
4+
5+
# Load settings from .env file, if it exists. If not, we'll use the
6+
# Puget Sound server URL (which is also the default in the SDK) and
7+
# the 'TEST' API key.
8+
settings = load_settings(
9+
{
10+
"api_key": "TEST",
11+
"base_url": "https://api.pugetsound.onebusaway.org/",
12+
}
13+
)
14+
15+
# Create a new instance of the OneBusAway SDK with the settings we loaded.
16+
oba = OnebusawaySDK(**settings)
17+
18+
# Define the query parameters
19+
query = {
20+
"tripId": "1_604670535", # Replace with actual trip ID
21+
"serviceDate": "1810918000000", # Replace with actual service date in milliseconds since epoch
22+
}
23+
24+
stopId = "1_75403" # Replace with actual stop ID
25+
26+
# Retrieve arrival and departure information
27+
response = oba.arrival_and_departure.list(stopId, extra_query=query)
28+
29+
# Example to access specific data
30+
arrivals_and_departures = response.data.entry.arrivals_and_departures
31+
32+
for arr_dep in arrivals_and_departures:
33+
print(f"Route: {arr_dep.route_short_name}")
34+
print(f"Trip Headsign: {arr_dep.trip_headsign}")
35+
print(f"Predicted Arrival Time: {arr_dep.predicted_arrival_time}")
36+
print(f"Scheduled Arrival Time: {arr_dep.scheduled_arrival_time}")
37+
print(f"Vehicle ID: {arr_dep.vehicle_id}")
38+
print("")

examples/config.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from pprint import pprint
2+
3+
from helpers.load_env import load_settings
4+
5+
from onebusaway import OnebusawaySDK
6+
7+
# Load settings from .env file, if it exists. If not, we'll use the
8+
# Puget Sound server URL (which is also the default in the SDK) and
9+
# the 'TEST' API key.
10+
settings = load_settings(
11+
{
12+
"api_key": "TEST",
13+
"base_url": "https://api.pugetsound.onebusaway.org/",
14+
}
15+
)
16+
17+
# Create a new instance of the OneBusAway SDK with the settings we loaded.
18+
oba = OnebusawaySDK(**settings)
19+
20+
response = oba.config.retrieve()
21+
pprint(response)

examples/current_time.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from pprint import pprint
2+
3+
from helpers.load_env import load_settings
4+
5+
from onebusaway import OnebusawaySDK
6+
7+
# Load settings from .env file, if it exists. If not, we'll use the
8+
# Puget Sound server URL (which is also the default in the SDK) and
9+
# the 'TEST' API key.
10+
settings = load_settings(
11+
{
12+
"api_key": "TEST",
13+
"base_url": "https://api.pugetsound.onebusaway.org/",
14+
}
15+
)
16+
17+
# Create a new instance of the OneBusAway SDK with the settings we loaded.
18+
oba = OnebusawaySDK(**settings)
19+
20+
response = oba.current_time.retrieve()
21+
pprint(response)

examples/helpers/load_env.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
from typing import Any, Dict, Optional
2+
from pathlib import Path
3+
4+
5+
def load_settings(default_settings: Dict[str, Any]) -> Dict[str, Any]:
6+
"""
7+
Load settings by merging default settings with environment variables.
8+
9+
Args:
10+
default_settings (Dict[str, Any]): The default settings to use.
11+
12+
Returns:
13+
Dict[str, Any]: The merged settings.
14+
"""
15+
env_variables = load_env()
16+
if env_variables:
17+
return {**default_settings, **env_variables}
18+
else:
19+
return default_settings
20+
21+
22+
def load_env() -> Optional[Dict[str, Any]]:
23+
"""
24+
Loads environment variables from a .env file located in the parent directory of the current file.
25+
26+
Returns:
27+
A dictionary containing the loaded environment variables, or None if the .env file does not exist.
28+
"""
29+
dirname = Path(__file__).resolve().parent
30+
env_path = dirname.parent / ".env"
31+
32+
if env_path.exists():
33+
return load_env_from_path(str(env_path))
34+
else:
35+
return None
36+
37+
38+
def load_env_from_path(file_path: str) -> Dict[str, str]:
39+
"""
40+
Load environment variables from a file.
41+
42+
Args:
43+
file_path (str): The path to the file containing environment variables.
44+
45+
Returns:
46+
dict: A dictionary containing the loaded environment variables, where the keys are the variable names
47+
and the values are the variable values.
48+
49+
"""
50+
env = {}
51+
with open(file_path, "r", encoding="utf8") as file:
52+
lines = file.readlines()
53+
54+
for line in lines:
55+
# Remove comments and trim whitespace
56+
trimmed_line = line.split("#")[0].strip()
57+
58+
if not trimmed_line:
59+
continue
60+
61+
key_value = trimmed_line.split("=", 1)
62+
if len(key_value) != 2:
63+
continue
64+
65+
key, value = key_value
66+
value = value.strip()
67+
68+
# Remove surrounding quotes if they exist
69+
if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")):
70+
value = value[1:-1]
71+
72+
env[key.strip()] = value
73+
74+
return env # type: ignore

examples/stop.py

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,24 @@
1-
import onebusaway
1+
from pprint import pprint
22

3+
from helpers.load_env import load_settings
34

4-
def main_sync() -> None:
5-
client = onebusaway.OnebusawaySDK(api_key="TEST")
6-
stop = client.stop.retrieve("1_75403")
5+
from onebusaway import OnebusawaySDK
76

8-
if stop.data and stop.data.entry:
9-
print(stop.data.entry)
10-
else:
11-
print("stop not found")
7+
# Load settings from .env file, if it exists. If not, we'll use the
8+
# Puget Sound server URL (which is also the default in the SDK) and
9+
# the 'TEST' API key.
10+
settings = load_settings(
11+
{
12+
"api_key": "TEST",
13+
"base_url": "https://api.pugetsound.onebusaway.org/",
14+
}
15+
)
1216

17+
# Create a new instance of the OneBusAway SDK with the settings we loaded.
18+
oba = OnebusawaySDK(**settings)
1319

14-
if __name__ == "__main__":
15-
main_sync()
20+
stop_id = "1_75403"
21+
stop = oba.stop.retrieve(stop_id)
22+
23+
if stop.data and stop.data.entry:
24+
pprint(stop.data.entry)

0 commit comments

Comments
 (0)