congress-py 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Antonio Alaniz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: congress-py
3
+ Version: 0.1.0
4
+ Summary: A lightweight Python SDK for interacting with the United States Congress API.
5
+ Author: Antonio Alaniz
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/talaniz/congress.py
8
+ Project-URL: Documentation, https://talaniz.github.io/congress.py/
9
+ Project-URL: Repository, https://github.com/talaniz/congress.py
10
+ Project-URL: Issues, https://github.com/talaniz/congress.py/issues
11
+ Project-URL: Changelog, https://github.com/talaniz/congress.py/blob/main/docs/changelog.md
12
+ Keywords: congress,api,legislative,government,sdk
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: requests<3,>=2.32.3
27
+ Requires-Dist: typer<1,>=0.12.5
28
+ Provides-Extra: dev
29
+ Requires-Dist: codecov<3,>=2.1.13; extra == "dev"
30
+ Requires-Dist: coverage<8,>=7.6.4; extra == "dev"
31
+ Requires-Dist: pytest<9,>=8.3.3; extra == "dev"
32
+ Requires-Dist: pytest-cov<7,>=6.0.0; extra == "dev"
33
+ Requires-Dist: requests-mock<2,>=1.12.1; extra == "dev"
34
+ Provides-Extra: docs
35
+ Requires-Dist: mkdocs<2,>=1.6.1; extra == "docs"
36
+ Requires-Dist: mkdocs-material<10,>=9.5.49; extra == "docs"
37
+ Requires-Dist: mkdocstrings[python]<1,>=0.27.1; extra == "docs"
38
+ Dynamic: license-file
39
+
40
+ # congress_py
41
+
42
+ ![Tests](https://github.com/talaniz/congress.py/actions/workflows/python-package.yml/badge.svg)
43
+
44
+ `congress_py` is an unofficial Python SDK and CLI for reading data from the
45
+ Congress.gov API.
46
+
47
+ This project is not affiliated with Congress.gov, the Library of Congress,
48
+ Congress, or the U.S. government. It does not provide legal, legislative,
49
+ lobbying, financial, compliance, or policy advice.
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install congress-py
55
+ ```
56
+
57
+ ### Local Development
58
+
59
+ ```bash
60
+ git clone https://github.com/talaniz/congress.py.git
61
+ cd congress.py
62
+ python3 -m venv .venv
63
+ .venv/bin/python -m pip install -e .
64
+ ```
65
+
66
+ You will need your own Congress.gov API key.
67
+
68
+ ## Documentation
69
+
70
+ Full documentation is available at:
71
+
72
+ https://talaniz.github.io/congress.py/
73
+
74
+ The documentation site includes installation steps, API-key setup, SDK examples,
75
+ CLI examples, API reference, contributing guidance, and the changelog.
76
+
77
+ ## License
78
+
79
+ MIT
@@ -0,0 +1,40 @@
1
+ # congress_py
2
+
3
+ ![Tests](https://github.com/talaniz/congress.py/actions/workflows/python-package.yml/badge.svg)
4
+
5
+ `congress_py` is an unofficial Python SDK and CLI for reading data from the
6
+ Congress.gov API.
7
+
8
+ This project is not affiliated with Congress.gov, the Library of Congress,
9
+ Congress, or the U.S. government. It does not provide legal, legislative,
10
+ lobbying, financial, compliance, or policy advice.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pip install congress-py
16
+ ```
17
+
18
+ ### Local Development
19
+
20
+ ```bash
21
+ git clone https://github.com/talaniz/congress.py.git
22
+ cd congress.py
23
+ python3 -m venv .venv
24
+ .venv/bin/python -m pip install -e .
25
+ ```
26
+
27
+ You will need your own Congress.gov API key.
28
+
29
+ ## Documentation
30
+
31
+ Full documentation is available at:
32
+
33
+ https://talaniz.github.io/congress.py/
34
+
35
+ The documentation site includes installation steps, API-key setup, SDK examples,
36
+ CLI examples, API reference, contributing guidance, and the changelog.
37
+
38
+ ## License
39
+
40
+ MIT
@@ -0,0 +1,59 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "congress-py"
7
+ version = "0.1.0"
8
+ description = "A lightweight Python SDK for interacting with the United States Congress API."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [
13
+ { name = "Antonio Alaniz" }
14
+ ]
15
+ keywords = ["congress", "api", "legislative", "government", "sdk"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Software Development :: Libraries :: Python Modules",
27
+ ]
28
+ dependencies = [
29
+ "requests>=2.32.3,<3",
30
+ "typer>=0.12.5,<1"
31
+ ]
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/talaniz/congress.py"
35
+ Documentation = "https://talaniz.github.io/congress.py/"
36
+ Repository = "https://github.com/talaniz/congress.py"
37
+ Issues = "https://github.com/talaniz/congress.py/issues"
38
+ Changelog = "https://github.com/talaniz/congress.py/blob/main/docs/changelog.md"
39
+
40
+ [project.optional-dependencies]
41
+ dev = [
42
+ "codecov>=2.1.13,<3",
43
+ "coverage>=7.6.4,<8",
44
+ "pytest>=8.3.3,<9",
45
+ "pytest-cov>=6.0.0,<7",
46
+ "requests-mock>=1.12.1,<2"
47
+ ]
48
+ docs = [
49
+ "mkdocs>=1.6.1,<2",
50
+ "mkdocs-material>=9.5.49,<10",
51
+ "mkdocstrings[python]>=0.27.1,<1"
52
+ ]
53
+
54
+ [tool.setuptools.packages.find]
55
+ where = ["src"]
56
+ include = ["congress_py*"]
57
+
58
+ [project.scripts]
59
+ congress = "congress_py.cli:run"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,8 @@
1
+ """Public package interface for congress_py."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from congress_py.client import CongressClient
6
+ from congress_py.models import Bill, BillAction, BillSummary
7
+
8
+ __all__ = ["Bill", "BillAction", "BillSummary", "CongressClient"]
@@ -0,0 +1,276 @@
1
+ """Command-line interface for congress_py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from dataclasses import asdict, is_dataclass
8
+ from pathlib import Path
9
+ from typing import Any, Optional
10
+
11
+ import typer
12
+
13
+ from congress_py.client import CongressClient
14
+ from congress_py.exceptions import MissingAPIKeyError
15
+
16
+ CONFIG_DIR = Path.home() / ".congress"
17
+ CONFIG_FILE = CONFIG_DIR / "config.toml"
18
+ MISSING_API_KEY_MESSAGE = (
19
+ "No Congress.gov API key found. Run congress configure or set CONGRESS_API_KEY."
20
+ )
21
+
22
+ app = typer.Typer(help="CLI for the Congress.gov API.")
23
+ congress_app = typer.Typer(help="Congress session commands.")
24
+ bills_app = typer.Typer(help="Bill commands.")
25
+
26
+
27
+ def _to_jsonable(value: Any) -> Any:
28
+ if is_dataclass(value):
29
+ return _to_jsonable(asdict(value))
30
+ if hasattr(value, "_asdict"):
31
+ return _to_jsonable(value._asdict())
32
+ if isinstance(value, dict):
33
+ return {key: _to_jsonable(item) for key, item in value.items()}
34
+ if isinstance(value, (list, tuple)):
35
+ return [_to_jsonable(item) for item in value]
36
+ return value
37
+
38
+
39
+ def _json_default(value: Any) -> Any:
40
+ converted = _to_jsonable(value)
41
+ if converted is not value:
42
+ return converted
43
+ raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
44
+
45
+
46
+ def _print_json(value: Any) -> None:
47
+ typer.echo(
48
+ json.dumps(_to_jsonable(value), default=_json_default, indent=2, sort_keys=True)
49
+ )
50
+
51
+
52
+ def _parse_simple_auth_toml(content: str) -> Optional[str]:
53
+ in_auth_section = False
54
+
55
+ for raw_line in content.splitlines():
56
+ line = raw_line.strip()
57
+ if not line or line.startswith("#"):
58
+ continue
59
+ if line.startswith("[") and line.endswith("]"):
60
+ in_auth_section = line == "[auth]"
61
+ continue
62
+ if not in_auth_section or "=" not in line:
63
+ continue
64
+
65
+ key, value = line.split("=", 1)
66
+ if key.strip() != "api_key":
67
+ continue
68
+ value = value.strip()
69
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
70
+ value = value[1:-1]
71
+ return value.strip() or None
72
+
73
+ return None
74
+
75
+
76
+ def _load_config_api_key(config_file: Optional[Path] = None) -> Optional[str]:
77
+ if config_file is None:
78
+ config_file = CONFIG_FILE
79
+
80
+ if not config_file.exists():
81
+ return None
82
+
83
+ content = config_file.read_text(encoding="utf-8")
84
+ try:
85
+ import tomllib
86
+ except ModuleNotFoundError:
87
+ return _parse_simple_auth_toml(content)
88
+
89
+ data = tomllib.loads(content)
90
+ auth = data.get("auth", {})
91
+ api_key = auth.get("api_key")
92
+ if isinstance(api_key, str):
93
+ return api_key.strip() or None
94
+ return None
95
+
96
+
97
+ def _resolve_api_key(explicit_api_key: Optional[str]) -> str:
98
+ if explicit_api_key:
99
+ return explicit_api_key
100
+
101
+ env_api_key = os.environ.get("CONGRESS_API_KEY")
102
+ if env_api_key:
103
+ return env_api_key
104
+
105
+ config_api_key = _load_config_api_key()
106
+ if config_api_key:
107
+ return config_api_key
108
+
109
+ raise MissingAPIKeyError(MISSING_API_KEY_MESSAGE)
110
+
111
+
112
+ def _get_client(ctx: typer.Context) -> CongressClient:
113
+ explicit_api_key = None
114
+ if ctx.obj:
115
+ explicit_api_key = ctx.obj.get("api_key")
116
+
117
+ try:
118
+ return CongressClient(api_key=_resolve_api_key(explicit_api_key))
119
+ except MissingAPIKeyError:
120
+ typer.echo(MISSING_API_KEY_MESSAGE, err=True)
121
+ raise typer.Exit(1)
122
+
123
+
124
+ def _toml_string(value: str) -> str:
125
+ return value.replace("\\", "\\\\").replace('"', '\\"')
126
+
127
+
128
+ @app.callback()
129
+ def main(
130
+ ctx: typer.Context,
131
+ api_key: Optional[str] = typer.Option(
132
+ None,
133
+ "--api-key",
134
+ help=(
135
+ "Congress.gov API key. Defaults to CONGRESS_API_KEY "
136
+ "or ~/.congress/config.toml."
137
+ ),
138
+ ),
139
+ ) -> None:
140
+ """Resolve global CLI options for all commands.
141
+
142
+ Args:
143
+ ctx: Typer context used to share resolved option values with commands.
144
+ api_key: Optional Congress.gov API key. If omitted, API commands fall
145
+ back to ``CONGRESS_API_KEY`` and then ``~/.congress/config.toml``.
146
+
147
+ """
148
+ ctx.obj = {"api_key": api_key}
149
+
150
+
151
+ @app.command()
152
+ def configure(
153
+ api_key: str = typer.Option(
154
+ ...,
155
+ "--api-key",
156
+ prompt=True,
157
+ hide_input=True,
158
+ help="Congress.gov API key to save locally.",
159
+ ),
160
+ ) -> None:
161
+ """Save a Congress.gov API key for future CLI commands.
162
+
163
+ Args:
164
+ api_key: Congress.gov API key to write to ``~/.congress/config.toml``.
165
+
166
+ """
167
+ CONFIG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
168
+ content = f'[auth]\napi_key = "{_toml_string(api_key)}"\n'
169
+
170
+ fd = os.open(CONFIG_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
171
+ with os.fdopen(fd, "w", encoding="utf-8") as config:
172
+ config.write(content)
173
+
174
+ try:
175
+ CONFIG_FILE.chmod(0o600)
176
+ except OSError:
177
+ pass
178
+
179
+ typer.echo("Configuration saved.")
180
+
181
+
182
+ @congress_app.command("current")
183
+ def congress_current(ctx: typer.Context) -> None:
184
+ """Return the current congressional session."""
185
+ client = _get_client(ctx)
186
+ _print_json(client.get_current_session())
187
+
188
+
189
+ @congress_app.command("list")
190
+ def congress_list(ctx: typer.Context) -> None:
191
+ """Return available congressional sessions."""
192
+ client = _get_client(ctx)
193
+ _print_json(client.get_congresses())
194
+
195
+
196
+ @bills_app.command("list")
197
+ def bills_list(
198
+ ctx: typer.Context,
199
+ session: Optional[int] = typer.Option(
200
+ None,
201
+ "--session",
202
+ help="Congress session number to pass to the existing SDK method.",
203
+ ),
204
+ limit: int = typer.Option(
205
+ 20,
206
+ "--limit",
207
+ min=1,
208
+ help="Number of bills to request per API call.",
209
+ ),
210
+ offset: int = typer.Option(
211
+ 0,
212
+ "--offset",
213
+ min=0,
214
+ help=(
215
+ "Starting offset for single-page mode. "
216
+ "Ignored when --pages is provided."
217
+ ),
218
+ ),
219
+ pages: Optional[int] = typer.Option(
220
+ None,
221
+ "--pages",
222
+ min=1,
223
+ help="Number of pages to fetch using the SDK iterator.",
224
+ ),
225
+ ) -> None:
226
+ """Return bills, optionally filtered by Congress session.
227
+
228
+ Args:
229
+ ctx: Typer context containing global CLI option values.
230
+ session: Optional Congress number used to filter bill results.
231
+ limit: Number of bills to request per API call.
232
+ offset: Starting offset for single-page results.
233
+ pages: Optional number of pages to fetch with the SDK iterator. When
234
+ provided, ``offset`` is ignored.
235
+
236
+ """
237
+ client = _get_client(ctx)
238
+ if pages is None:
239
+ bills = client.get_bills(session=session, limit=limit, offset=offset)
240
+ else:
241
+ bills = list(client.iter_bills(session=session, limit=limit, max_pages=pages))
242
+ _print_json(bills)
243
+
244
+
245
+ @bills_app.command("get")
246
+ def bills_get(ctx: typer.Context, congress: int, bill_type: str, number: int) -> None:
247
+ """Return one bill by congress, bill type, and number."""
248
+ client = _get_client(ctx)
249
+ _print_json(client.get_bill(congress, bill_type, number))
250
+
251
+
252
+ @bills_app.command("actions")
253
+ def bills_actions(
254
+ ctx: typer.Context, congress: int, bill_type: str, number: int
255
+ ) -> None:
256
+ """Return actions for one bill."""
257
+ client = _get_client(ctx)
258
+ _print_json(client.get_bill_actions(congress, bill_type, number))
259
+
260
+
261
+ @bills_app.command("summaries")
262
+ def bills_summaries(
263
+ ctx: typer.Context, congress: int, bill_type: str, number: int
264
+ ) -> None:
265
+ """Return summaries for one bill."""
266
+ client = _get_client(ctx)
267
+ _print_json(client.get_bill_summaries(congress, bill_type, number))
268
+
269
+
270
+ app.add_typer(congress_app, name="congress")
271
+ app.add_typer(bills_app, name="bills")
272
+
273
+
274
+ def run() -> None:
275
+ """Run the Typer application."""
276
+ app()