Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
72.7 kB

afeld/sodapy

Project Overview

sodapy is a Python client library for the Socrata Open Data API (SODA), the interface that exposes the open data portals hosted on Socrata domains such as data.edmonton.ca or sandbox.demo.socrata.com. Its purpose is to give Python developers a thin, idiomatic wrapper around Socrata's HTTP endpoints so that public open datasets can be discovered, queried, and published without hand-crafting requests. The package is small and dependency-light, relying on requests for transport.

The scope covers both read and write workflows. On the read side, a client can enumerate the datasets available on a domain, fetch a single record or a page of records with SoQL-style filtering (where, order, limit, offset, select, exclude_system_fields), iterate lazily over every row of a resource via a generator that pages through results, retrieve and update dataset metadata, and download a dataset's attachments. On the write side it supports creating, publishing, and permissioning datasets, upserting and replacing rows from Python objects or CSV files, creating and replacing non-data file datasets, and deleting individual rows or entire datasets.

Architecturally the library centers on the Socrata class in sodapy/socrata.py, a context-manager-friendly object that owns a configured requests.Session carrying the X-App-token header, basic-auth or OAuth bearer credentials, an optional custom session adapter for proxies or non-HTTPS transports, and a numeric timeout. Shared helpers in sodapy/utils.py handle authentication validation, request and response processing, and payload normalization, while sodapy/constants.py holds reusable path templates. Tests under tests/ and Jupyter notebooks in examples/ demonstrate typical usage.

Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.

Submission Constraints (read carefully — the evaluation depends on these)

This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:

  1. Do NOT create or modify any files under the test directories (e.g. tests/, test/, testing/, or files named test_*.py / conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.

  2. Your package MUST be importable by the name the tests use. The hidden tests import your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid pyproject.toml / setup.py / setup.cfg and lay out your modules so that pip install -e . succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.

  3. Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.

Install / Reconstruction Contract

Follow this contract before implementing the documented APIs:

  • Project root: /workspace/repo at runtime; the submitted repository root is ..
  • Package/distribution name: sodapy
  • Package roots: .
  • Install strategy: editable-install
  • Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
  • Provision commands:
    python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
    programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; }
    export -f programgen_pip_install
    programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
    programgen_pip_install python3 -m pip install 'setuptools >= 77.0.3'
    (
    programgen_install_report="$(mktemp)"
    trap 'rm -f "$programgen_install_report"' EXIT
    SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report"
    python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n    metadata=item.get('"'"'metadata'"'"', {})\n    name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n    provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n    selected={'"'"''"'"'} | (provided & requested)\n    parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n    while True:\n        added=set()\n        for requirement in parsed:\n            if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n                continue\n            if canonicalize_name(requirement.name)==name:\n                if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n                    raise ValueError('"'"'local extra requires a different target distribution'"'"')\n                extras={canonicalize_name(value) for value in requirement.extras}\n                if not extras <= provided:\n                    raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n                added.update(extras - selected)\n        if not added:\n            break\n        selected.update(added)\n    for requirement in parsed:\n        if canonicalize_name(requirement.name)==name:\n            continue\n        if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n            requirement.marker=None\n            requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report"
    )
    
  • Runtime setup:
    {
      [ -e "$PWD"/README.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; };
      SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps;
    }
    
  • Project root for installation: .
  • Build-version environment: SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0, PDM_BUILD_SCM_VERSION=0.0.0, POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0, UV_DYNAMIC_VERSIONING_BYPASS=0.0.0
  • Test directory: tests
  • Test command: bash -lc 'set -uo pipefail run=(python3 -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_socrata.py tests/test_utils.py tests/test_version.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_socrata.py tests/test_utils.py tests/test_version.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_socrata.py tests/test_utils.py tests/test_version.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?'
  • Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.

Environment & Project Structure

  • Language: python
  • Build system: python
  • Test command: bash -lc set -uo pipefail run=(python3 -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_socrata.py tests/test_utils.py tests/test_version.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_socrata.py tests/test_utils.py tests/test_version.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_socrata.py tests/test_utils.py tests/test_version.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?

Project Directory Structure

.github/dependabot.yml
.github/workflows/tests.yml
.gitignore
.vscode/extensions.json
.vscode/settings.json
CHANGELOG.md
CODE_OF_CONDUCT.md
CONTRIBUTING.md
LICENSE
README.md
examples/basic_queries.ipynb
examples/basic_queries.py
examples/socrata_interface.png
examples/soql_queries.ipynb
examples/soql_queries.py
pyproject.toml
sodapy/__init__.py
sodapy/constants.py
sodapy/socrata.py
sodapy/utils.py
uv.lock

API Usage Guide

Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.

Capability: Client setup and session lifecycle

Purpose and scope

Socrata.__init__ is the single construction point of the library. Every other capability — catalog search, row reads, metadata, writes — assumes an instance whose session, domain, uri_prefix, and timeout are already populated. Construction performs no network I/O: it allocates a requests.Session, decorates it with credentials, optionally mounts a transport adapter, and records the timeout. That property is what lets tests build clients against a fake domain such as fakedomain.com with a mock adapter and never touch the network.

Construction sequence and ordering

The order of the steps is observable and therefore part of the contract:

  1. Domain check. A falsy domain (missing, None, empty string) fails immediately, before any session exists. Only truthiness is tested; the value is stored verbatim, with no scheme stripping and no trailing-slash normalization. Hosts are expected to be bare hosts, because request URLs are composed as uri_prefix + domain + path; passing https://data.cityofnewyork.us would yield a malformed URL.
  2. Session allocation. self.session is always a fresh requests.Session() — never shared or module-level — so headers and auth on one client cannot leak into another.
  3. App token. When the token is falsy, no header is set and a throttling warning is emitted by the stdlib logging module — specifically the module-level logging.warning(...) call inside sodapy/socrata.py. Because no getLogger(__name__) is involved, the record is dispatched through the root logger and is recorded under the logger name "root", not "sodapy.socrata"; tests observe it via caplog/logging capture and must not filter on a library-named logger. It is still invisible to pytest.warns, since no warnings.warn is used. When truthy, the header X-App-token is set to the value verbatim.
  4. Credential validation. Exactly one credential mode may be supplied: basic auth requires both username and password (one without the other is an error), and neither may be combined with an OAuth access token. This rule set is not implemented in Socrata; it is delegated to the module helper utils.authentication_validation(username, password, access_token), called with the three raw arguments (never the session) after the app-token step and before any credential is attached. Ownership of the credential error contract — exception type and message — therefore lives in sodapy.utils, and its placement between the header and auth steps is what makes the ordering observable.
  5. Credential application. Basic auth becomes session.auth = (username, password); otherwise a truthy access token becomes an Authorization header whose value is "OAuth " + token (Socrata's scheme, one space, not Bearer). The branch is elif, so basic auth would win if both were present — but step 4 makes that unreachable.
  6. Adapter mounting. A supplied session adapter is a mapping with exactly the keys prefix and adapter; the client calls session.mount(prefix, adapter) and records uri_prefix = prefix. Because the same value is used for both the mount and uri_prefix, and every request URL is built as uri_prefix + domain + path, the mounted prefix is by construction a prefix of every composed URL, so the mounted adapter is always the one that handles the client's traffic. With no adapter — a falsy session_adapter, i.e. no mapping — nothing is mounted, uri_prefix stays the literal "https://", and requests' own default https:// adapter is used. (Note that requests registers defaults for both https:// and http:// and raises InvalidSchema when no registered mount matches a URL; that path is not reachable from within this client, since uri_prefix always matches the composed URLs.)
  7. Timeout validation. The timeout is checked last with isinstance(timeout, (int, float)). Ints and floats are stored on self.timeout and forwarded as the timeout= keyword of each request; strings such as "fail" or "10" are rejected with the documented TypeError. Booleans pass, since bool subclasses int.

Because the timeout check comes last, an invalid timeout combined with an invalid credential pair surfaces the authentication error instead, and any adapter already mounted is discarded with the half-built object. Callers must not rely on partial construction being rolled back.

Defaults

  • timeout defaults to 10 seconds, in seconds, for every request issued by the client.
  • No adapter means HTTPS transport and uri_prefix == "https://".
  • app_token=None is legal (rate-limited access), as is access_token=None with no username/password (anonymous access).
  • DEFAULT_LIMIT is a class-level constant equal to 1000, shared by all instances and read by the paging generator; it is never mutated per client.

Lifecycle

__enter__ returns self, so with Socrata(...) as client: binds the client object, never the underlying session. __exit__ accepts the three exception arguments (all defaulted, so it may also be called directly), calls close(), and returns None — a falsy result — so exceptions raised inside the block propagate unchanged and are never suppressed. Teardown therefore happens on both the success and the failure path.

close() only calls session.close(). It is idempotent and merely shuts down the session's connection pools; it clears no headers, auth, uri_prefix, domain, or timeout. The session and the client remain fully usable afterwards — new connections are created lazily on the next request — so calling close() twice, or reusing a client whose with block has already exited, is safe and does not require constructing a replacement client.

If construction fails — bad domain, bad credentials, non-numeric timeout — __enter__ never runs, so no close() is attempted on the partially built object. Tests that wrap construction in with observe only the construction error.

Test-sensitive details

  • Error classes must match exactly: the missing-domain failure is a plain Exception, while the timeout failure is a TypeError. Raising TypeError for a missing domain would satisfy a broad pytest.raises(Exception) yet violate the contract.
  • Both failures carry fixed messages; tests assert those messages.
  • Construction must be free of network effects and must tolerate unreachable domains.
  • Two clients must not share a session, headers, or auth state.
  • The app-token warning is a root-logger record observed through logging capture, not through pytest.warns.
  • import sodapy must expose Socrata and a string __version__ without constructing anything.
  • uri_prefix is public state that callers and tests inspect to confirm adapter wiring; keep it equal to the mount prefix, not a derived value.
  • The timeout is applied per request, so a client-level value is the only place timeouts are configured; there is no per-call override in this capability.

Exact API Reference

sodapy.socrata.Socrata

  • Import Path: from sodapy.socrata import Socrata
  • Required Test Import Paths:
    • sodapy.Socrata
  • Exact Test Import Statements:
    • from sodapy import Socrata
  • Kind: class
  • Signature:
class Socrata:
    DEFAULT_LIMIT: int
    def __init__(self, domain, app_token, username=None, password=None, access_token=None, session_adapter=None, timeout=10)
    def __enter__(self)
    def __exit__(self, _exc_type=None, _exc_value=None, _traceback=None)
    def datasets(self, limit=0, offset=0, order=None, **kwargs)
    def create(self, name, **kwargs)
    def set_permission(self, dataset_identifier, permission='private', content_type='json')
    def get_metadata(self, dataset_identifier, content_type='json')
    def update_metadata(self, dataset_identifier, update_fields, content_type='json')
    def download_attachments(self, dataset_identifier, content_type='json', download_dir='~/sodapy_downloads')
    def publish(self, dataset_identifier, content_type='json')
    def get(self, dataset_identifier, content_type='json', **kwargs)
    def get_all(self, *args, **kwargs)
    def upsert(self, dataset_identifier, payload, content_type='json')
    def replace(self, dataset_identifier, payload, content_type='json')
    def create_non_data_file(self, params, file_data)
    def replace_non_data_file(self, dataset_identifier, params, file_data)
    def delete(self, dataset_identifier, row_id=None, content_type='json')
    def close(self)
    domain: Any
    session: Any
    timeout: Any
    uri_prefix: Any
  • Raises (implementation must reproduce these exact messages):
    • A domain is required.
    • Timeout must be numeric.
  • Behavior: The main class that interacts with the SODA API. Sample usage:

sodapy.__version__

  • Import Path: from sodapy import __version__
  • Required Test Import Paths:
    • sodapy.version
  • Exact Test Import Statements:
    • import sodapy
  • Kind: constant
  • Signature:
__version__: str
  • Behavior: Module-level value required by the test import contract.

Capability: Authentication and credential validation

Purpose

Credential validation is a pure, side-effect-free gate that decides whether a caller's credential combination is coherent before any request is built. It answers three questions with a single outcome shape (raise or return): are the basic-auth parts supplied as a pair, and is more than one authentication mechanism being requested at once? Everything the client does later with session.auth or an Authorization header depends on this gate having run first, so its conditions are the contract that makes the rest of the credential handling unambiguous.

Where it sits in the client workflow

The check is invoked from the client constructor at a deliberately chosen point in the setup sequence:

  1. domain presence is asserted (empty/missing domain aborts before anything is configured);
  2. the application token is handled -- absent token logs a throttling warning, present token adds the X-App-token header to the session;
  3. the validation gate runs, using only username, password and access_token (the app token is never inspected here);
  4. credentials are actually applied to the session from mutually exclusive branches: a truthy username and truthy password install a basic-auth tuple, otherwise a truthy access token installs the OAuth-style Authorization header;
  5. transport concerns follow (adapter mounting, URI prefix, timeout type check).

Two consequences of that ordering are test-visible. First, an invalid credential combination raises while the object is still being constructed, so no usable client is returned and a with block never enters its body. Second, the gate runs after the app-token header is attached but before any credential is attached, so a rejected combination never leaves a partially authenticated session; the discarded requests.Session carried only an app token, not credentials. The gate itself must not attach anything to a session, log, or mutate its arguments -- it is a predicate expressed as an exception.

Truthiness semantics (the core rule)

Both conditions are evaluated on truthiness, not identity with None. Practical matrix, with u/p/t for username/password/access_token:

u p t Outcome
falsy falsy falsy accepted (anonymous / app-token-only access)
falsy falsy truthy accepted (OAuth path)
truthy truthy falsy accepted (basic path)
truthy falsy any rejected: basic pair incomplete
falsy truthy any rejected: basic pair incomplete
truthy truthy truthy rejected: mixed mechanisms

Empty string, None, 0 and False are all treated as "not supplied". A whitespace-only string is truthy and therefore counts as supplied. Non-string truthy objects are also accepted by the predicate (it never coerces or type-checks), and only later does requests care whether the basic-auth tuple contains usable values.

Ordering matters between the two rejections

The incomplete-pair test is evaluated first, and the mixed-mechanism test second. That ordering is observable: supplying only username together with an access_token fails the first condition, not the mixed-auth one, even though both are technically true-ish violations. Reordering or fusing the two conditions into one message would change which diagnostic a caller sees and break message-sensitive assertions. The second condition is written as two disjuncts over username and password each paired with the token; because the first condition has already guaranteed that the two are supplied together or not at all, reaching it implies a complete basic pair plus a token. Note that an empty-string token does not trip the mixed check, since it is falsy.

Edge cases worth preserving

  • No credential combination is "fixed up": a lone username is never silently dropped, and a token is never silently preferred over basic credentials.
  • (falsy, falsy, falsy) and (truthy, truthy, falsy) and (falsy, falsy, truthy) are the three accepted shapes; there is no fourth accepted shape and no ordering-dependent acceptance.
  • The function returns nothing on success. Callers must detect validity by absence of an exception, not by a return value; a helper that returned a boolean would not match call sites that just call it and continue.
  • Because it is a module-level utility, it can be reused by third parties to pre-validate before constructing a client, and its argument order (username, password, access_token) is positional in that use.
  • The raised type is the generic exception type, not a subclass of ValueError; catch code should not assume a narrower class.
  • Application tokens are outside this capability entirely: a missing app token is only warned about in the client layer, never rejected here. Do not add app-token validation to the gate, or token-less clients that tests expect to build successfully will start failing.

Reimplementation constraints

Keep the gate as one function with the two checks in the original order, driven by truthiness, with distinct messages per violation and no side effects. Call it from the constructor at the same position in the sequence, after app-token setup and before credential assignment, and keep the credential assignment branches mutually exclusive so the gate's guarantee (never both mechanisms) is what makes the elif safe. Preserve the generic exception type and the parameter names used positionally by existing call sites.

Exact API Reference

sodapy.utils.authentication_validation

  • Import Path: from sodapy.utils import authentication_validation
  • Required Test Import Paths:
    • sodapy.utils.authentication_validation
  • Exact Test Import Statements:
    • import sodapy.utils as utils
  • Kind: function
  • Signature:
def authentication_validation(username, password, access_token)
  • Raises (implementation must reproduce these exact messages):
    • Basic authentication requires a username AND password.
    • Cannot use both Basic Authentication and OAuth2.0. Please use only one authentication method.
  • Behavior: Only accept one form of authentication.

Capability: API request routing and URL formatting

API request routing and URL formatting

Purpose and layering

Every request the client makes funnels through one private dispatcher, _perform_request(request_type, resource, **kwargs). Everything upstream of it produces only a relative resource path (never a full URL) plus the keyword arguments that will be forwarded to requests. A faithful re-implementation must preserve this split:

  • The shared builders take their path fragments from sodapy.constants: that module is the single source for DEFAULT_API_PATH ("/resource/", trailing slash, because the dataset id is concatenated straight onto it), OLD_API_PATH ("/api/views", no trailing slash, because the separator is inserted conditionally), and DATASETS_PATH = "/api/catalog/v1". It is not the only place path text appears, however: the client module also embeds literal fragments of its own (the /api/imports2/ endpoint and the attachment-path shapes), so nothing should assume every URL fragment is importable from the constants module.
  • Two builders in sodapy.utils convert (dataset id, optional row id, content type) into a relative path for either the modern SoQL API or the legacy views API.
  • clear_empty_values strips None-valued keys so "not supplied" never reaches the wire, while deliberately keeping other falsy values.
  • _perform_request composes the absolute URI, dispatches the verb, checks status, and normalizes the body.
  • download_file is the one path that bypasses the configured session entirely.

The two path families

The four legacy combinations are: id + content type gives /api/views/{id}.{content_type}; id alone gives /api/views/{id}; content type alone gives /api/views.{content_type} (no slash — this is how a not-yet-created dataset is addressed); supplying neither is an error. Note the asymmetry: the content-type-only form is legal here.

The modern builder is stricter. It emits output only when both a dataset id and a content type are present; a row id alone, an id without a content type, or a content type without an id all fall through to the same error message as the legacy builder. With a row id it produces /resource/{id}/{row_id}.{content_type}; without one, /resource/{id}.{content_type}. The row id is inserted between the id and the dotted suffix, so the suffix always attaches to the final path segment.

Both builders signal the invalid combinations with a plain, un-subclassed Exception carrying the message quoted above — not a ValueError or TypeError — so callers (and tests) must catch Exception rather than a narrower type.

URI assembly and dispatch

_perform_request validates the verb against the allowed set get/post/put/delete and raises for anything else (the message is built by joining that set, so do not depend on member ordering — only on the raised type and the stable prefix). The absolute URI is a plain triple concatenation of uri_prefix, domain, and resource: no slash is inserted, nothing is URL-encoded or normalized, so each caller owns its own formatting. uri_prefix is https:// for a default client, or the adapter's prefix string verbatim when a session adapter was mounted — an adapter prefix must therefore already carry its scheme.

The dispatcher always overwrites kwargs["timeout"] with the client timeout, so per-call timeouts are impossible. Only statuses 200 and 202 count as success; anything else is handed to utils.raise_for_status. That helper is narrower than "raises on any non-success status": it builds an HTTPError only for 4xx ("Client Error") and 5xx ("Server Error") responses, optionally appending the JSON message field when it differs from the reason, and then raises requests.exceptions.HTTPError. For every other non-200/202 status — a 3xx redirect, or a non-4xx/5xx code such as 204 — it builds no message, returns None, and is therefore a silent no-op, after which execution falls through to the content-type body-decoding branch on a response the client never treated as successful. An empty response body short-circuits and returns the raw requests.Response — this is why delete and set_permission return response objects rather than data.

Otherwise the body is decoded by the response's content-type header, looked up and .strip().lower()ed: a regex match on application/(vnd.geo+)?json (via re.match, so ; charset=... suffixes still match) returns parsed JSON; text/csv is parsed into a list of string lists via csv.reader over StringIO; any content type containing xml returns raw bytes from response.content; text/plain attempts json.loads and falls back to the text; anything else raises an "Unknown response format" error. A response without a content-type header raises AttributeError before reaching that last branch, so stubbed responses in tests must set the header.

Routing map

Operation Verb Family
datasets GET /api/catalog/v1
get GET modern
upsert POST modern
replace PUT modern
delete with row id DELETE modern (with row segment)
delete without row id DELETE legacy
get_metadata GET legacy
update_metadata PUT legacy
set_permission PUT legacy
create POST legacy, content-type-only form
publish POST legacy base + /publication.{content_type}
replace_non_data_file POST legacy with txt
create_non_data_file POST literal /api/imports2/

Non-obvious behaviors

create formats /api/views.json and, when new_backend is requested, appends a raw query string to the resource (?nbe=true) rather than passing params; the concatenation is naive, so nothing in the path may already contain ?. publish string-formats the legacy base with the content type after a slash. delete selects its family by the truthiness of the row id, so a falsy row id (including 0) silently routes to the whole-dataset legacy path. set_permission sends the legacy path with query parameters method=setPermission and value, where public is translated to public.read and any other value passes through unchanged. replace_non_data_file forces method=replaceBlob and copies the dataset id into an id parameter. create_non_data_file bypasses the builders entirely with the literal /api/imports2/.

download_attachments hand-assembles URIs and hands them to download_file, which issues a bare streaming requests.get — no app token, no basic auth or OAuth header, no timeout — and writes 1024-byte chunks in binary mode, skipping empty keep-alive chunks. It never validates the response: raise_for_status is not called and the function returns None, so a 4xx/5xx error body is written verbatim into local_filename and no error is ever surfaced to the caller. The attachment path shape depends on whether the attachment carries an assetId (legacy /api/views/{id}/files/{assetId}?download=true&filename={filename}) or only a blobId (/api/assets/{blobId}?download=true).

_perform_update is payload shaping only and never touches the URL: a dict or list is JSON-dumped into data, an IOBase instance is sent as a raw body with a content-type: text/csv header (so CSV uploads carry the file object itself, not a parsed structure), and any other payload type raises an unsupported-payload error.

Defaults worth pinning

Every public method that takes a content type defaults it to "json"; passing an explicit None makes the modern builder (and therefore get, upsert, replace, row-level delete) raise instead of guessing. get builds its SoQL parameter dictionary with $-prefixed keys ($select, $where, $order, $group, $limit, $offset, $q, $query, $$exclude_system_fields), pops format out as an Accept header, then merges leftover keyword arguments in as additional raw query parameters before filtering Nones — so arbitrary field-name filters survive while omitted ones vanish. Because filtering happens after the merge, a caller may override a canonical parameter by passing the same $-key explicitly.

Exact API Reference

sodapy.utils.clear_empty_values

  • Import Path: from sodapy.utils import clear_empty_values
  • Required Test Import Paths:
    • sodapy.utils.clear_empty_values
  • Exact Test Import Statements:
    • import sodapy.utils as utils
  • Kind: function
  • Signature:
def clear_empty_values(args)
  • Behavior: Scrap junk data from a dict.

sodapy.utils.format_old_api_request

  • Import Path: from sodapy.utils import format_old_api_request
  • Required Test Import Paths:
    • sodapy.utils.format_old_api_request
  • Exact Test Import Statements:
    • import sodapy.utils as utils
  • Kind: function
  • Signature:
def format_old_api_request(dataid=None, content_type=None)
  • Raises (implementation must reproduce these exact messages):
    • This method requires at least a dataset_id or content_type.

sodapy.utils.format_new_api_request

  • Import Path: from sodapy.utils import format_new_api_request
  • Required Test Import Paths:
    • sodapy.utils.format_new_api_request
  • Exact Test Import Statements:
    • import sodapy.utils as utils
  • Kind: function
  • Signature:
def format_new_api_request(dataid=None, row_id=None, content_type=None)
  • Raises (implementation must reproduce these exact messages):
    • This method requires at least a dataset_id or content_type.

sodapy.utils.download_file

  • Import Path: from sodapy.utils import download_file
  • Required Test Import Paths:
    • sodapy.utils.download_file
  • Exact Test Import Statements:
    • import sodapy.utils as utils
  • Kind: function
  • Signature:
def download_file(url, local_filename)
  • Behavior: Utility function that downloads a chunked response from the specified url to a local path.

sodapy.constants.DEFAULT_API_PATH

  • Import Path: from sodapy.constants import DEFAULT_API_PATH
  • Required Test Import Paths:
    • sodapy.constants.DEFAULT_API_PATH
  • Exact Test Import Statements:
    • from sodapy.constants import DEFAULT_API_PATH, OLD_API_PATH
  • Kind: constant
  • Signature:
DEFAULT_API_PATH: str
  • Behavior: Module-level value required by the test import contract.

sodapy.constants.OLD_API_PATH

  • Import Path: from sodapy.constants import OLD_API_PATH
  • Required Test Import Paths:
    • sodapy.constants.OLD_API_PATH
  • Exact Test Import Statements:
    • from sodapy.constants import DEFAULT_API_PATH, OLD_API_PATH
  • Kind: constant
  • Signature:
OLD_API_PATH: str
  • Behavior: Module-level value required by the test import contract.

Capability: Response decoding and error handling

Purpose

Most public methods — the data and metadata calls — route through the single private request executor (Socrata._perform_request), which owns two responsibilities: decide whether an HTTP response represents a failure, and convert a successful response body into the Python value callers expect. sodapy.utils.raise_for_status is deliberately separate from requests.Response.raise_for_status: it builds a Socrata-flavoured message, appends the API's own error text when available, and raises requests.exceptions.HTTPError while attaching the response object.

download_attachments is the documented exception and does not pass through the executor: it calls sodapy.utils.download_file, which issues requests.get(url, stream=True) and writes chunks to disk. It never calls raise_for_status, and none of the decoding dispatch, content-type handling, or error classification described below applies to it — a failed attachment download produces no exception from this machinery and is only observable through the written file.

Ordering inside the request executor

The steps are strictly ordered and each one is test-observable:

  1. Validate the verb. Only get, post, put, delete are accepted; anything else raises a generic Exception naming the supported set before any network call. The supported set is a Python set, so the message's verb list is in arbitrary (not alphabetical) order.
  2. Build the URI from uri_prefix (custom adapter prefix or https://), domain, and the already-formatted resource.
  3. Inject timeout=self.timeout into the call kwargs, overwriting anything a caller passed. Dispatch happens via getattr(self.session, request_type).
  4. Error check: if response.status_code is neither 200 nor 202, call utils.raise_for_status(response). Note 202 Accepted is treated as success, which matters for asynchronous write endpoints (create/publish/upsert).
  5. Empty-body short circuit: if not response.text, return the raw requests.Response object. This is why delete, set_permission, and other body-less calls hand back a response whose .status_code is asserted in tests rather than a dict. Be careful that the truthiness test is on decoded text, not content, so a zero-length body of any content type takes this branch.
  6. Content-type dispatch on response.headers.get("content-type").strip().lower().

Because step 4 precedes step 5, a failure always raises even when the failing response has an empty body.

Error classification rules

raise_for_status inspects response.status_code and builds the prefix:

  • 400 <= status < 500 → "{status} Client Error: {reason}".
  • 500 <= status < 600 → "{status} Server Error: {reason}".
  • Anything else (1xx/2xx/3xx, or >= 600) leaves the message empty, so no exception is raised and the function returns None. This tolerance is what allows the executor's explicit (200, 202) allow-list to be the primary gate while still being safe if it is called with an unusual status.

The reason phrase is interpolated verbatim, so a synthetic response with reason = "Test Error" yields e.g. "400 Client Error: Test Error".

When reason is absent

The two absence cases behave differently and both deserve care:

  • Empty-string reason (reason = ""): interpolation appends nothing, so the message ends with the literal separator ": " (for example "400 Client Error: "). Being falsy but still a str, it keeps a working .lower(), so the enrichment guard below is safe.
  • reason is None, which is the default on a bare requests.Response: None is interpolated literally, producing "400 Client Error: None" / "500 Server Error: None". If the JSON body yields a truthy message, the guard more_info.lower() != response.reason.lower() raises an uncaught AttributeError (NoneType has no lower), so no HTTPError is ever constructed and the AttributeError propagates instead. A response with reason = None and no usable JSON message still raises the expected HTTPError, but with "None" embedded in its text.

Enrichment step: only when a prefix was built, the code tries response.json().get("message") inside a try/except ValueError. Three outcomes must be kept distinct:

  • Non-JSON body (the usual HTML or plain-text error page): response.json() raises ValueError, which is caught, leaves more_info unset, and the prefix-only HTTPError is still raised. Error handling is unaffected by such bodies.
  • JSON document that is not a mapping (for example a top-level list returned by an error endpoint): response.json() succeeds, .get is not an attribute of the parsed list, and the resulting AttributeError is not caught, because only ValueError is. It escapes before the HTTPError is constructed, so no HTTPError is produced.
  • JSON object with a message: when that message is truthy and its lowercased form differs from the lowercased reason, the message is extended with ".\n\t" + more_info — a period, newline, and a literal tab. The lowercase comparison prevents duplicating text such as 404 Not Found where the JSON message merely restates the reason. (This comparison also triggers the reason is None AttributeError described above; that failure is again uncaught.)

Finally requests.exceptions.HTTPError(http_error_msg, response=response) is raised, so exc.response is available and pytest.raises(..., match=...) can assert on the leading "{status} {Client|Server} Error: {reason}" fragment.

Decoding dispatch

Matching uses re.match (anchored at the start of the header value) after stripping and lowercasing, so charset parameters are harmless:

  • application/json and application/vnd.geo+json → response.json(), returning whatever the document holds (usually a list[dict] for row queries, a dict for metadata/catalog responses). A caller-supplied Accept header (the format kwarg) does not change this branch.
  • text/csv → the body is wrapped in StringIO and parsed with csv.reader, returning a list[list[str]] with no header handling, no type coercion, and no dict rows. Every field is a string; get_all iterating a CSV response therefore yields lists, not dicts.
  • any header containing xml → response.content, i.e. raw bytes. This is the only branch returning bytes; tests assert on the type/bytes value returned by get(..., content_type="xml").
  • text/plain → opportunistically parsed: json.loads(response.text) when the body happens to be valid JSON (so plain-text endpoints that emit scalar or object JSON come back as Python objects); otherwise the raw string. Only ValueError is caught, which is exactly what json.loads raises for malformed input.
  • Anything else, including application/octet-stream or a missing/blank content-type, raises Exception("Unknown response format: {content_type}"). Note the header lookup is not guarded: if the server omits content-type entirely, .strip() on None raises AttributeError before this message can be produced. The reported content type is the normalized (stripped, lowercased) value, not the raw header.

Order matters: JSON is tested before CSV, XML, and plain text; text/plain is checked last, so a header like application/json never reaches the JSON-parsing fallback of the plain-text branch.

Interaction with callers

  • get, get_all, datasets, get_metadata, update_metadata, publish, set_permission, delete all return the decoded value (or the raw response for empty bodies).
  • get_all depends on the decoded value supporting len() and iteration, so JSON lists and CSV row lists work; code should not assume get_all is meaningful for XML bytes.
  • download_attachments bypasses this machinery entirely: it uses sodapy.utils.download_file with requests.get(..., stream=True) and never calls raise_for_status, so a failed attachment download is not signalled by an exception from the decoder.
  • Write endpoints that respond 202 with an empty body return the Response; callers awaiting a payload must check for that case.

Test-sensitive behaviours to reproduce exactly

  • The Client Error / Server Error wording, the ": " separator, and the ".\n\t" enrichment separator.
  • Raising only for 4xx/5xx; returning None (no raise) for other codes passed directly to the helper.
  • Attaching response=response to HTTPError.
  • Accepting 202 as success and raising for every other non-200/202 code, including 3xx.
  • Interpolating a None reason literally as "None", and letting a truthy JSON message combined with reason = None raise an uncaught AttributeError rather than an HTTPError; likewise letting a non-mapping JSON error body raise an uncaught AttributeError.
  • Returning the Response object (not None, not a dict) when response.text is empty.
  • Returning a list-of-lists for CSV, bytes for XML, parsed JSON for application/json/vnd.geo+json, and either parsed JSON or the raw string for text/plain.
  • Raising Exception with the Unknown response format: ... message for unrecognized content types.

Exact API Reference

sodapy.utils.raise_for_status

  • Import Path: from sodapy.utils import raise_for_status
  • Required Test Import Paths:
    • sodapy.utils.raise_for_status
  • Exact Test Import Statements:
    • import sodapy.utils as utils
  • Kind: function
  • Signature:
def raise_for_status(response)
  • Behavior: Custom raise_for_status with more appropriate error message.

Capability: Additional components

Purpose

This capability covers the package-level surface that the test suite touches outside the individual helpers: the top-level sodapy package object (its re-export, its public export list, and its version attribute) and the sodapy.utils submodule as an independently importable namespace. Nothing here performs work on its own; the point is that both import statements succeed in a clean interpreter, expose exactly the expected attributes, and carry no import-time side effects that would disturb the test run.

Role in realistic workflows

A caller never composes these pieces directly; they are the seams the rest of the library hangs from.

  1. import sodapy (or from sodapy import Socrata) must resolve without contacting a Socrata domain. Import-time work is limited to importing the client class and binding the version string, so constructing a client later is the first place configuration, credentials, and transport are considered.
  2. sodapy.Socrata is the same object as sodapy.socrata.Socrata. Because the name is re-exported rather than redefined, isinstance checks, monkeypatching of sodapy.socrata.Socrata, and subclasses all behave consistently: patching the defining module is visible through the package attribute only if the patch happens before the from ... import binding, so tests that need to intercept client behaviour should patch where it is looked up.
  3. sodapy.__all__ is the curated public list. It exists so star-imports and documentation tooling see the client class and not the private module names (sodapy.socrata, sodapy.utils, sodapy.constants) that the package imports as a side effect of loading.
  4. import sodapy.utils as utils gives tests a direct handle on the helper layer. Test code frequently calls the helpers in isolation, feeding hand-built requests.models.Response objects or a requests_mock.Mocker() context, and it deliberately goes through the submodule rather than through Socrata so that helper semantics can be asserted without any HTTP session, credentials, or dataset id.

State and ordering

  • Both imports are pure: no session is created, no token is read, no file is opened, no network call is issued. Importing sodapy.utils pulls in requests and the shared path constants, and importing sodapy additionally pulls in the client module. That is the whole transitive closure.
  • sodapy.utils is reachable in two ways: explicitly via import sodapy.utils, and implicitly as an attribute of the package once sodapy has been imported, because loading the client module imports the helper module. Code should not depend on the implicit form; the explicit import is what the tests use and what survives refactoring of the client module's internals.
  • Attribute binding happens once, at first import, and is cached in sys.modules. Rebinding sodapy.Socrata or sodapy.__version__ at runtime affects only the package namespace, not the defining module, and does not persist across a fresh interpreter.
  • __version__ is a plain string attribute on the package, so it is available without importlib.metadata lookups and without the installed distribution metadata being importable. It is the single source of truth for the release version: the build configuration reads it dynamically through an attribute reference rather than declaring a literal, so editing the version literal is the only place a release changes. It must be a plain semantic-version triple: exactly three dot-separated components, each of which is numeric, so suffixes such as 2.2.0rc1 fail.
  • __all__ is a one-element list of strings; the packaging import target and the export list are both resolved by attribute name, so a typo in either breaks star-imports or the build rather than any runtime call.

Defaults and edge cases

  • This layer is thin on parameters but not free of them, so the documented entry conditions must be read against real signatures. Both path builders declare keyword defaults of None — the old-API builder takes dataid=None, content_type=None, and the new-API builder takes dataid=None, row_id=None, content_type=None — which is why either can be invoked with no arguments at all and then raise, and why callers routinely use the keyword form or fill in only part of the parameter list. The remaining callables declare no defaults of their own and take plain positional arguments: the status raiser (a response), the empty-value scrubber (a mapping of args), the credential validator (username, password, and access token), and the downloader (url and local filename). At the package level the only literals are the export list containing a single name and the version literal.
  • Star-import (from sodapy import *) yields only Socrata; __version__ is intentionally not in __all__ and must be accessed as an attribute.
  • Importing a deeper submodule first (import sodapy.utils) also executes the package __init__, so the client module is imported in every case; a failure inside the client module surfaces on any sodapy.* import, not only on import sodapy.
  • Helper functions are module-level attributes, so they can be captured by reference before a test and compared afterwards; the helpers hold no module-level mutable state between calls, which is why parametrized tests can call them repeatedly with unrelated inputs.
  • The helper layer assumes it may receive a requests response object that was never sent over a socket (status code and reason assigned by hand). It must therefore not require attributes only a real response has, and must tolerate a body that is not JSON.

Test-sensitive behaviour

  • A status outside the 4xx/5xx ranges must be treated as success and return None silently; only those two ranges raise, and the message must embed the numeric code, the category wording, and the response reason so the test's regular-expression match succeeds.
  • When the body carries a JSON message field that differs from the reason (case-insensitively), the raised error text appends it after the base message; identical or absent messages leave the base text untouched, and a non-JSON body must not raise a decode error out of the helper.
  • Empty-value scrubbing removes only None; empty strings, 0, False, and empty containers are preserved verbatim, and the returned mapping is a new dict rather than the argument mutated in place.
  • The two path builders guard their inputs differently and both raise the generic exception (not a subclass) when those inputs are insufficient, emitting leading-slash paths composed from the shared constants rather than hard-coded strings. The old-API builder treats a lone dataset id (a path of the dataset under the old base) or a lone content type (the old base suffixed with that content type) as usable and raises only when both are None. The new-API builder requires a dataset id and a content type together: it raises whenever either one is missing, and it silently ignores a row id unless the content type is also present, in which case the row id is spliced into the path before the extension.
  • Credential validation accepts exactly one scheme: username with password, or a lone token; any mix, or a half-specified basic pair, raises. Supplying no credentials at all is also accepted silently — with all three arguments falsy there is nothing to validate and the call returns None without raising. The guards are truthiness-based rather than presence-based, so an empty-string token or an empty-string credential counts as absent (a full username/password pair alongside an empty-string token passes, exactly as the credential-free call does).
  • The chunked download helper writes bytes to the exact local path given, creating nothing else, and skips empty keep-alive chunks so the resulting file matches the served body byte for byte.

Usage remains as in the reference below.

Exact API Reference

sodapy.utils

  • Import Path: from sodapy import utils
  • Required Test Import Paths:
    • sodapy.utils
  • Exact Test Import Statements:
    • import sodapy.utils as utils
  • Kind: module
  • Behavior: Module required during hidden-test collection.

sodapy

  • Import Path: sodapy
  • Required Test Import Paths:
    • sodapy
  • Exact Test Import Statements:
    • import sodapy
  • Kind: module
  • Behavior: Module required during hidden-test collection.

Detailed Implementation Nodes

Node: Client setup and session lifecycle

Functional constraints

  • Constructor order is fixed: domain truthiness check -> new requests.Session -> X-App-token header or root-logger logging.warning -> credential validation via utils.authentication_validation(username, password, access_token) -> basic auth or OAuth header -> adapter mount plus uri_prefix -> timeout type check -> store timeout. The timeout check must be last.
  • Credential validation is delegated: Socrata itself implements none of the username/password/access-token rules, it just calls the sodapy.utils helper with the three raw arguments before touching credentials on the session.
  • The missing-app-token warning goes out on the root logger (module-level logging.warning), so its record name is "root"; no named library logger is created for it.
  • The session must never be module-level or shared between instances; each client owns its own pools.
  • Request URL composition everywhere is uri_prefix + domain + path, with uri_prefix equal to the adapter prefix when supplied and "https://" otherwise; since the mount prefix and uri_prefix are the same value, the mounted adapter always handles the client's requests. The only non-mount case is a falsy session_adapter.
  • __enter__ returns the client itself. __exit__ closes and returns a falsy value so in-block exceptions propagate untouched.
  • close() closes only the session, is idempotent, and leaves every other attribute intact; the client stays usable for further requests afterwards.
  • No DNS resolution, socket, or HTTP call may occur during construction.
  • Keep DEFAULT_LIMIT = 1000 as a class attribute; keep sodapy.__version__ a string and re-export Socrata from the package root.

Usage example

import requests
from sodapy import Socrata

class Stub(requests.adapters.BaseAdapter):
    def send(self, request, **kwargs):
        raise AssertionError("no network during setup")

adapter = {"prefix": "http://", "adapter": Stub()}
client = Socrata("fakedomain.com", "token", session_adapter=adapter, timeout=5)
assert client.uri_prefix == "http://"
assert client.session.headers["X-App-token"] == "token"
with client as c:
    assert c is client
client.close()

Node: Authentication and credential validation

Functional constraints

  • Signature: authentication_validation(username, password, access_token); positionally callable; parameter names part of the contract.
  • Pure predicate: no mutation of arguments, no session/header/logging side effects, no return value used.
  • Check 1 (first): reject when exactly one of username/password is truthy -- i.e. bool(username) != bool(password). Any access_token value is irrelevant to this branch.
  • Check 2 (second): reject when a truthy access_token co-occurs with a truthy username or a truthy password; because check 1 ran first, reaching this implies a complete basic pair plus a token.
  • Two distinct error messages, one per violation, in the original order: which one surfaces is part of the observable behavior.
  • Generic exception type; no custom subclass.
  • Accepted-only shapes: (falsy, falsy, falsy), (truthy, truthy, falsy), (falsy, falsy, truthy).
  • None, "", 0, False count as unsupplied; whitespace-only strings and other truthy objects count as supplied. No type coercion or type checking.
  • Never inspect or validate the application token here.

Integration constraints

  • Call it from the client constructor after the X-App-token header is set and before credentials are attached, so failures raise before any request and leave no partially authenticated session.
  • Attach exactly one mechanism afterwards: basic-auth tuple when username and password are both truthy, else the OAuth bearer header when the token is truthy; do not attach both.
  • Keep appending subsequent setup (adapter, URI prefix, timeout type check) after this gate; do not reorder it.

Usage

import sodapy.utils as utils

utils.authentication_validation(None, None, "oauth-token")  # accepted (OAuth)
utils.authentication_validation("user", "secret", None)     # accepted (basic)
utils.authentication_validation(None, None, None)           # accepted (anonymous)

# Violation 1: incomplete basic pair -- its own block.
try:
    utils.authentication_validation("user", None, None)
except Exception as exc:
    print(exc)  # incomplete-pair diagnostic

# Violation 2: mixed mechanisms -- a separate, independent block.
try:
    utils.authentication_validation("user", "secret", "tok")
except Exception as exc:
    print(exc)  # mixed-mechanism diagnostic

The two rejection cases must be demonstrated in separate try/except blocks (or separate sequential snippets), never inside one shared try. The incomplete-pair call raises at check 1, which terminates control flow for that call, so a mixed-mechanism call placed after it in the same block is never executed and its diagnostic would be unobservable; the first raise must therefore be isolated from the second call so each violation is reached in its own run.

Node: API request routing and URL formatting

  • Produce relative paths only; the dispatcher owns uri_prefix + domain + resource with plain string concatenation (no added slashes, no encoding).
  • DEFAULT_API_PATH must keep its trailing slash and OLD_API_PATH must not gain one; the dotted content-type suffix is appended with a literal . in both families.
  • Legacy builder: id+type -> {OLD}/{id}.{type}; id only -> {OLD}/{id}; type only -> {OLD}.{type}; neither -> raise.
  • Modern builder: requires id AND type; optional row id yields {DEFAULT}{id}/{row}.{type} (row id inserted between the id and the dotted content-type suffix), otherwise {DEFAULT}{id}.{type}; every other combination raises the same message as the legacy builder.
  • Both builders raise a plain, un-subclassed Exception with the message This method requires at least a dataset_id or content_type. — never a ValueError or TypeError — so consumers must catch Exception itself.
  • clear_empty_values keeps keys whose value is not None (preserving insertion order) and must retain 0, "", False, and empty containers; it never mutates the input.
  • Dispatcher accepts only get/post/put/delete, always overrides timeout, treats 200 and 202 as success, and returns the Response untouched when the body is empty.
  • raise_for_status raises HTTPError only for 4xx/5xx and silently returns None for any other non-success status (3xx, 204, ...), which then falls through to the content-type decoding branch.
  • Body decoding keys off the stripped, lowercased content-type header: JSON (including vnd.geo+json and charset suffixes), CSV to list-of-lists, XML to bytes, text/plain to JSON-or-text, else raise.
  • download_file uses a fresh streaming requests.get (no session, no headers, no timeout), performs no status validation, returns None, and writes non-empty 1024-byte chunks in binary mode — so non-2xx bodies are persisted silently.
  • Route selection is per method: modern for get/upsert/replace/row delete; legacy for metadata, permissions, create, publish, file replacement; literal /api/imports2/ for non-data-file creation; /api/catalog/v1 for catalog listing.
  • delete picks the family by row-id truthiness; create appends ?nbe=true directly onto the path; set_permission maps public to public.read.
import sodapy.utils as utils

utils.format_old_api_request(dataid="nimj-3ivp", content_type="json")  # '/api/views/nimj-3ivp.json'
utils.format_old_api_request(content_type="json")                      # '/api/views.json'
utils.format_new_api_request(dataid="nimj-3ivp", row_id=4, content_type="json")  # '/resource/nimj-3ivp/4.json'
utils.format_new_api_request(dataid="nimj-3ivp", content_type="csv")  # '/resource/nimj-3ivp.csv'
utils.clear_empty_values({"$limit": 0, "$where": None, "$q": ""})   # {'$limit': 0, '$q': ''}

Node: Response decoding and error handling

Functional constraints

  • Expose one helper, raise_for_status(response), in sodapy.utils; it must not delegate to requests.Response.raise_for_status.
  • Classification: 400 <= status < 500 → "{status} Client Error: {reason}"; 500 <= status < 600 → "{status} Server Error: {reason}"; any other status produces no message and returns None without raising.
  • reason is formatted verbatim: an empty string leaves a trailing ": ", while None is rendered as the text "None".
  • Enrichment runs only when a prefix exists: attempt response.json().get("message") under except ValueError. A ValueError leaves more_info unset and the HTTPError is still raised. A JSON document that is not a mapping raises an uncaught AttributeError at .get, before the HTTPError is constructed. A truthy message whose lowercase differs from response.reason.lower() is appended as ".\n\t" + message; when reason is None this comparison raises an uncaught AttributeError instead of raising HTTPError.
  • Raise requests.exceptions.HTTPError(message, response=response) so callers can inspect exc.response.
  • In the request executor, call the helper when status_code not in (200, 202); return the raw response before decoding when not response.text.
  • The executor path covers the data/metadata methods only; download_attachments goes through sodapy.utils.download_file (requests.get(..., stream=True) plus chunked file writes) and neither invokes the executor, the decoder, nor raise_for_status.
  • Decoding is on response.headers.get("content-type").strip().lower(), matched with re.match in this order: application/(vnd.geo+)?json → response.json(); text/csv → list(csv.reader(StringIO(response.text))) (list of lists of strings, no header/type coercion); header containing xml → response.content (bytes); text/plain → json.loads(response.text) falling back to response.text on ValueError; otherwise raise Exception("Unknown response format: {content_type}").
  • Keep the timeout injection and verb allow-list (get, post, put, delete) ahead of dispatch, so invalid verbs fail before any HTTP call.

Usage example

import requests
from sodapy import Socrata
from sodapy import utils

client = Socrata("sandbox.demo.socrata.com", None)

rows = client.get("nimj-3ivp", limit=5)          # application/json -> list[dict]
csv_rows = client.get("nimj-3ivp", content_type="csv")  # list[list[str]]
raw_xml = client.get("nimj-3ivp", content_type="xml")   # bytes

try:
    client.get("does-not-exist")
except requests.exceptions.HTTPError as exc:
    print(exc)                 # "404 Client Error: Not Found" (+ ".\n\t" + API message)
    print(exc.response.status_code)

try:
    utils.raise_for_status(some_response)
except requests.exceptions.HTTPError as exc:
    raise

Node: Additional components

  • Package module sodapy/__init__.py must import the client class from its defining module and bind it as Socrata, define __all__ as a list containing only that name, and define __version__ as a string of exactly three dot-separated all-numeric components, which the build configuration picks up via an attribute reference.
  • The package must be importable with no network access, no credentials, no environment variables, and no filesystem writes; import-time work is limited to loading the client and helper modules.
  • sodapy.utils must be a real submodule whose module-level callables are plain functions with no shared mutable state, importable both explicitly and as a package attribute.
  • Helper module imports only requests and the shared path constants; it must not import the client class (avoiding a circular import) and must not create a session.
  • Functions must accept hand-constructed response objects and must not assume a live socket, JSON body, or specific headers.
  • Parameter defaults must be declared as optional None values on the two path builders (dataset id and content type on the old-API builder; dataset id, row id, and content type on the new-API builder) so that each can be called with no arguments, while the status raiser, scrubber, credential validator, and downloader take plain positional arguments with no defaults.
  • Range handling: 4xx and 5xx raise requests.exceptions.HTTPError carrying the response; all other codes return None. The message is a client-error form or a server-error form built from the code and reason, optionally extended with the body's JSON message when that message differs from the reason case-insensitively.
  • Empty-value scrubbing returns a new dict dropping only entries whose value is None; falsy-but-present values are kept.
  • Path builders return strings beginning with a slash, built from the shared constants, and raise a bare Exception when their required inputs are missing — but the requirement is builder-specific: the old-API builder returns for a dataset id alone or a content type alone and raises only when both are None, whereas the new-API builder returns only when a dataset id and a content type are both supplied (appending the row id in that branch only when a row id is present) and raises whenever either the dataset id or the content type is missing.
  • Credential validation raises a bare Exception for a username without password (and vice versa) and for any truthy credential combined with a truthy access token; a lone token or a full username/password pair passes, and a call with no credentials at all is a no-op that returns None. Because the guards test truthiness, empty strings count as absent on both sides of the exclusivity checks.