Skip to content

Let a JSON API source quote several fields (#179, item 2) - #189

Merged
caufieldjh merged 3 commits into
mainfrom
caufieldjh/json-api-multiple-fields
Dec 3, 2026
Merged

caufieldjh merged 3 commits into
mainfrom
caufieldjh/json-api-multiple-fields

Conversation

@caufieldjh

@caufieldjh caufieldjh commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Addresses item 2 of #179. Item 1 (XML via url:) landed in #188. The third ask in the issue comments, a non-JSON source built from a URL template, is not in this PR.

Problem

A configured JSON API source's content took one JSONPath and kept only its first match. Facts spread across a record, such as openFDA's device_class and regulation_number, never reached the cached text and could not be quoted. A JSON-derived record was also always labelled abstract_only, so a failed quote carried a misleading "only abstract available" note. This is the same mislabelling #164 fixed for Wikipedia.

Change

  • content may be a list or a labelled mapping, not just one JSONPath:
    sources:
      FDA_PRODUCT_CODE:
        url_template: "https://api.fda.gov/device/classification.json?search=product_code:{id}"
        fields:
          title: "$.results[0].device_name"
          content:
            Device name: "$.results[0].device_name"
            Device class: "$.results[0].device_class"
            Regulation number: "$.results[0].regulation_number"
    This is cached as one Label: value line per field, in order. A list gives bare values, one per line. Each path is read through extract_extra_fields, the same reader source_extra_fields uses: first match only, a list value's items joined with spaces, and an empty value left out, label included. A single-path content is unchanged.
  • content_type: a list or mapping defaults to full_text, since a record isn't an abstract. A single path stays abstract_only, as before. A new optional content_type key (abstract_only | full_text) overrides either default.
  • source_extra_fields is now honoured for a configured source's prefix. Its fields are appended under ### name headings and recorded in extra_fields_captured, as for DOI, PMID and ClinicalTrials.
  • Config validation: only content takes a list or mapping, and every JSONPath must parse. The check (json_api_field_problem in models.py) runs in JSONAPISourceConfig.__post_init__, so a config built in code raises ValueError. The YAML loader builds the config and turns that ValueError into a warning that skips the source, so one set of rules covers both. An unknown content_type is treated the same way.

Behaviour change (for release notes)

A configured JSON API source with an invalid JSONPath in any field (including single-path title, year and the rest) is now skipped at load with a warning naming the path, and that prefix is unavailable until the path is fixed. Before, such a source loaded, and only that field came back empty. Building a JSONAPISourceConfig with such a path in Python now raises ValueError.

Design choice to review

The full_text default for list and mapping content is a judgement call. The alternative is no default: list and mapping forms would stay abstract_only unless content_type: full_text is set, and the FDA example would then show the misleading abstract note unless configured.

Cache

No cache version bump. An entry already cached keeps its text. After changing a source's fields, cache reference PREFIX:ID --force refetches it. This was checked live: a single-path EBF entry was rewritten with the labelled lines as full_text. The docs say so.

Tests

  • tests/test_json_api_multiple_fields.py (new) uses the real openFDA EBF record (tests/fixtures/json_api/, fetched 2026-11-30, with the openfda lists cut to 3 entries). It covers:
    • loading from YAML, including sources: in the main config file
    • the malformed shapes that are rejected, and content_type validation
    • label lines, list form, dropping empty fields, list values, and the first match of a wildcard
    • the content_type defaults and override
    • source_extra_fields: appended, alone, and for another prefix
    • save → reload → find_text_in_reference for each field, served from the cache
    • no abstract note on a failed quote
  • The existing tests/test_json_api_source.py (30 tests) is unchanged and passes.
  • Locally, the new and related source and loader tests pass (92), as do just doctest (351), just mypy and just format.
  • test_wikipedia_source.py fails on and off on my machine with connect timeouts to its own 127.0.0.1 test server. wikipedia.py is untouched; I'm leaving that to CI.
  • Live check through the CLI against api.fda.gov: Device class: 2 and Regulation number: 872.3690 are valid. Device class: 3 is invalid, with no abstract note.

Docs

docs/how-to/add-reference-source.md has a new "Quoting several fields" section, and its config table lists content_type.

🤖 Generated with Claude Code

content took one JSONPath and kept its first match, so facts spread across
a record (openFDA's device_class and regulation_number) could not be
quoted. content may now also be a list of JSONPaths, one value per line,
or a mapping of labels to JSONPaths, one "Label: value" line each. Each
path is read as source_extra_fields reads one, and an empty value leaves
no label behind.

A list or mapping is a record, not an abstract, so it is cached as
full_text: a failed quote no longer says "only abstract available". A
single path stays abstract_only. A new content_type key overrides either.
source_extra_fields is now honoured for a configured source's prefix, and
a source with a malformed fields entry or content_type is skipped at load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 1s —— View job


I'll analyze this and get back to you.

5 similar comments
@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 1s —— View job


I'll analyze this and get back to you.

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 1s —— View job


I'll analyze this and get back to you.

@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 1s —— View job


I'll analyze this and get back to you.

@claude

claude Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 1s —— View job


I'll analyze this and get back to you.

@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 1s —— View job


I'll analyze this and get back to you.

@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 47s —— View job


PR review: JSON API source quoting several fields (#179, item 2)

  • Read the diff: json_api.py, loader.py, models.py, docs
  • Check that it reuses extract_extra_fields correctly
  • Run tests: not done, because uv isn't installed on this runner. These notes come only from reading the code and doctests.

Summary

This is a clean, small change. The best choice here is reusing extract_extra_fields in _record_text. That gives the content list/mapping the same rules as source_extra_fields: first match, list values joined with spaces, empty values dropped, bad JSONPath logged and skipped. Users then have one set of rules to learn. Shape checks in the loader catch bad config at load, docstrings and doctests are thorough, and the cache caveat is documented. I found no blocking issues.

On the design choice you raised (full_text default)

I agree with full_text for list and mapping content. A labelled record is the whole of what the API returns, so "only abstract available" would be wrong in almost every case. The way to override it is clear, and it's documented. Keeping single-path content as abstract_only keeps existing behaviour, which is the right call.

Smaller points (nits / possible follow-ups)

  1. Invalid JSONPath is only found at fetch time. _field_spec_problem (loader.py) checks shapes but not syntax. If the path in content: {Device class: "$.results[[0"} is bad, the source still loads. At fetch, extract_extra_fields logs a warning and drops that line without failing. The PR says such problems now fail "at load rather than during a fetch", but that only covers shapes. A jsonpath_parse call on each path inside _field_spec_problem would close the gap cheaply. Fix this →

  2. Building JSONAPISourceConfig in code skips validation. It's a plain dataclass, so only configs loaded from YAML are checked. Two cases:

    • A config with content_type="fulltext" is passed straight into ReferenceContent.
    • A config with fields={"title": ["$.a"]} quietly goes through _record_text, because _extract_fields sends every field that isn't a string there, not just content.

    A __post_init__ that calls _field_spec_problem and checks JSON_API_CONTENT_TYPES would apply the same rules to both paths. Low priority, since YAML is the documented way in.

  3. Single-path and multi-path reads differ slightly. Single-path content still uses _jsonpath_extract, while list/mapping uses extract_extra_fields. Any difference in how they handle a list value or a whitespace-only value now depends on the config's shape. That's fine to keep for backward compatibility, but a sentence in the _record_text docstring or the docs would head off surprises.

  4. No content, but extra fields present. If content resolves to None and source_extra_fields captured something, the record gets the configured default type. For a single-path source that's abstract_only, labelling text that is only ### name sections. This case is rare and arguably fine, but a test pinning the intended behaviour would help.

  5. Typing: JSONAPIFieldSpec widens every entry of fields, so mypy can't tell that title, authors and the other fields are always str. That's acceptable. A comment on JSONAPIFieldSpec that only content may be non-string would help readers (the comment on the fields attribute partly says this already).

Performance / security

  • A path is parsed again for each field on each fetch, which is the same as the existing extra-fields code. It's negligible next to the HTTP call.
  • No new security surface. Labels are only used as text, and {id} substitution and header interpolation are unchanged.

Test coverage

Coverage looks strong for what the PR describes:

  • a real openFDA fixture
  • loader rejection cases
  • content_type defaults and override
  • source_extra_fields, including the case where another prefix's fields are not used
  • save → reload → find_text_in_reference round trip
  • no abstract note on a failed quote

Suggested additions: an invalid-JSONPath-in-mapping case (pairs with point 1) and the case in point 4.

I agree with leaving the flaky test_wikipedia_source.py to CI, since wikipedia.py isn't touched.


A source whose JSONPath did not parse still loaded, and lost its line at
fetch time; a config built in Python skipped every check. The field check
now also parses each path, lives in models as json_api_field_problem, and
runs from JSONAPISourceConfig.__post_init__ as well as the YAML loader,
which still turns a problem into a warning and a skipped source.

Also pins the type of a record whose only text is source_extra_fields
(the source's default, as DOI and PMID do), and documents how a
single-path content reads a list or blank value differently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@caufieldjh

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All five points are addressed in 1c8bfbc.

  1. JSONPath syntax at load: done. json_api_field_problem (moved from loader.py to models.py) now parses every path. A typo such as $.results[[0 drops the source at load with a warning, for a mapping, a list or a single path. Tested.
  2. Configs built in code: done. JSONAPISourceConfig.__post_init__ runs the same check and the content_type check, and raises ValueError. So fields={"title": ["$.a"]} and content_type="fulltext" can no longer reach _record_text or ReferenceContent. Tested, plus a doctest.
  3. Single-path vs multi-path reads: documented in _record_text, with the actual difference checked. A single-path content keeps its older _jsonpath_extract reading for compatibility: a list value comes out as ['K1', 'K2'], and a whitespace-only value is kept rather than dropped.
  4. Extra fields alone: pinned. The record takes the source's own default: abstract_only for a single path and full_text for a list or mapping. That matches how DOI and PMID label extra fields alone. Tested both ways.
  5. JSONAPIFieldSpec: the comment now says every field other than content is always a string, enforced by the check.

The PR description's validation bullet is updated to match. Locally after the change: 100 targeted tests pass, just doctest 352, and just mypy and just format are clean.

@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 46s —— View job


PR review: JSON API source quoting several fields (#179, item 2): follow-up after 1c8bfbc

  • Read the diff, focusing on 1c8bfbc, which responds to the earlier review
  • Run tests: not done, because uv isn't on this runner and jsonpath_ng isn't installed. These notes come from reading the code and doctests.
  • Post the review

Summary

The new commit deals with every point from the last review:

Earlier point Status
1. Invalid JSONPath only found at fetch time ✅ json_api_field_problem (models.py) now parses every path
2. Config built in code skips validation ✅ JSONAPISourceConfig.__post_init__ runs the same field check and content_type check, and raises ValueError
3. Single-path and multi-path reads differ ✅ explained in the _record_text docstring (list printed as Python repr, whitespace kept)
4. No content, but extra fields present ✅ pinned with a test: the source's default type, as DOI and PMID do
5. JSONAPIFieldSpec typing ✅ comment says only content may be non-string

The checks now live in one place in models.py, and the loader and the dataclass both call them. That's better than the earlier copy kept only in the loader: the YAML loader turns a problem into a warning and skips the source, and code gets an exception. I see no blocking issues.

Points to consider

  1. Behaviour change for existing single-path configs (worth a changelog line). json_api_field_problem parses every path, including plain strings for title, authors and year. Before this PR, a source with a bad path in, say, year still loaded, and only that field came back None. Now the loader skips the whole source with a warning, and a config built in code raises. That's stricter and probably right. But a user whose config used to half-work will now find the prefix missing, so it's worth one line in the release notes. (src/linkml_reference_validator/models.py ~L874–915)

  2. Two checks, two orders. _parse_source_config (loader.py ~L239–251) runs json_api_field_problem and the content_type check, and then __post_init__ runs both again when the dataclass is built. The second run can't fail, so this is only duplicate code, not a bug. If you want one source of truth, the loader could catch the ValueError from the constructor:

    try:  # config comes from user YAML
        return JSONAPISourceConfig(...)
    except ValueError as exc:
        logger.warning(f"{exc}; source skipped")
        return None

    CLAUDE.md is wary of try/except. This one wraps user input, though, so it's arguably justified. Keeping it as it is works fine too.

  3. Formatting nit: in models.py there's only one blank line between the JSONAPIFieldSpec = ... assignment and def json_api_field_problem. PEP 8 / E302 wants two. just format runs only ruff check with the default rules, which don't include E302, so CI won't catch it. ruff format would fix it.

  4. A JSONPath that matches an object. extract_extra_fields turns a matched dict into text with str(...), so content: {Device: "$.results[0]"} gives a line like Device: {'device_name': ...}. That's the same as the existing source_extra_fields behaviour, so it isn't new. A sentence in the docs ("point each path at a scalar or a list of scalars") would head off confusion. The model's source_extra_fields description already says something similar.

  5. source_extra_fields paths are still not checked at load. Content paths now fail early, but a bad source_extra_fields path for a JSON API prefix is still only logged at fetch time. That's existing behaviour, shared with DOI, PMID and ClinicalTrials, so it's out of scope here. Mentioning it only for consistency.

Code quality

  • _record_text keys the list form by position ({str(i): path}), so a path listed twice is read twice. That's a nice touch, and it's commented.
  • _content_type uses the explicit content_type first, then falls back to the shape of content. It's simple and has doctests.
  • Using isinstance(spec, dict/list) works with ruamel's CommentedMap/CommentedSeq, which subclass dict/list. A YAML label that parses as a number (2020: "$.x") is rejected with a clear message.
  • The try/except around jsonpath_parse in json_api_field_problem is justified, and its comment says why ("parsing is the only way to know a path is valid").

Performance / security

  • Paths are now parsed once more when the config is built, which is negligible. There's no new security surface: labels are used only as text, and URL and header handling haven't changed.

Test coverage

There are 24 tests in tests/test_json_api_multiple_fields.py, with doctests for the new checks covering:

  • an invalid path in a mapping
  • non-content lists
  • empty list or mapping
  • a code-built config raising ValueError

One more test could pin point 1: a single-string field with an invalid path (e.g. title: "$.[[bad") now skips the source in the loader and raises in code. That's the behaviour change most likely to surprise someone.

Verdict

Ready to merge from my side. Point 1 is worth noting in the changelog; the rest are optional nits.

…view)

The loader ran json_api_field_problem and the content_type check, then
__post_init__ ran both again. It now builds the config and turns the
ValueError into its warning, so YAML and code meet one set of rules. Adds
a test that a bad single path is now refused, documents that change, and
says to point each path at a value rather than an object.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 25s —— View job


PR review: JSON API source quoting several fields (#179, item 2): follow-up after 113af64

  • Read the new commit (113af64) against the last review
  • Run tests: not done, because uv isn't on this runner. These notes come from reading the code.
  • Post the review

What changed since the last review

Earlier point Status
1. Stricter loading for a bad single path ✅ Documented in docs/how-to/add-reference-source.md, with the before/after spelled out. Pinned by a bad-single-path case in test_a_config_built_in_code_is_checked_too. The loader side is already covered by test_an_invalid_jsonpath_drops_the_source_at_load.
2. Two checks, two orders ✅ _parse_source_config (loader.py:245-260) now builds the config and turns its ValueError into a warning. JSONAPISourceConfig.__post_init__ is the only place the rule lives. The unused JSON_API_CONTENT_TYPES / json_api_field_problem imports are gone.
3. E302 blank line in models.py ✅ Fixed
4. A path that matches an object ✅ Docs say "Point each path at a value or a list of values" and show the {'device_name': ...} output
5. source_extra_fields checked only at fetch Out of scope, as agreed

Notes on the new code

  • The try/except is justified. It wraps user-supplied YAML at a system boundary, the comment says so, and it catches only ValueError. That fits the CLAUDE.md guidance.
  • The warning text still names the source. __post_init__ puts JSON API source 'X': field 'title' … in its message, so f"{e}; source skipped" still tells the user which prefix and field were dropped. The existing caplog checks ("X", "JSONPath", "content_type") still hold.
  • Small catch-scope point. The try also covers the other constructor arguments. Today none of them raise ValueError (bool(store_raw) can't fail that way), so this is safe. If __post_init__ later checks other things, such as url_template lacking {id}, those checks will get the same skip-with-warning handling for free. That's probably what you want.
  • Minor and optional. The warning wording changed slightly, from Source 'X' field 'title' … to JSON API source 'X': field 'title' …. It's harmless, but anyone grepping logs for the old phrasing would miss it.

Performance / security

Nothing new. Each path is now parsed once at load instead of twice.

Test coverage

The rejection cases now go through both the YAML loader and the in-code dataclass for:

  • a malformed shape
  • an invalid path (mapping, list or single path)
  • an unknown content_type

I have no further gaps to suggest.

Verdict

Every point from both earlier reviews has been dealt with. I have no blocking or non-blocking issues left, so this looks ready to merge from my side.

@caufieldjh

Copy link
Copy Markdown
Contributor Author

Follow-up points, in 113af64:

  1. Behaviour change: recorded in a new "Behaviour change (for release notes)" section of the PR description (the repo has no changelog file) and in docs/how-to/add-reference-source.md. The test you suggested is added: a bad single-path title now raises when the config is built in code, and the loader test already covered skipping it at load.
  2. One check, not two: taken. _parse_source_config no longer repeats the checks. It builds the config and turns __post_init__'s ValueError into its warning (JSON API source 'X': field 'content' must not be empty; source skipped), with the try/except commented as a boundary for user-supplied YAML.
  3. E302: fixed by hand. I didn't run ruff format over models.py, because that would reformat the whole file.
  4. Paths matching an object: the docs now say to point each path at a value or a list of values, and show what an object turns into.
  5. source_extra_fields paths not checked at load: left as is, since it's shared with DOI, PMID and ClinicalTrials and out of scope here.

Locally: 101 targeted tests, just doctest 352, and just mypy and just format are clean.

@caufieldjh
caufieldjh merged commit c98c546 into main Dec 3, 2026
7 checks passed
@caufieldjh
caufieldjh deleted the caufieldjh/json-api-multiple-fields branch December 3, 2026 19:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant