openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Volumes multiget JSON API /api/volumes/.../json/{req}.json fails to return metadata due to regex parsing issue

Open RsbhThakur opened this issue 5 months ago • 5 comments

Problem

The volumes multiget API endpoint (/api/volumes/{brief_or_full}/json/{req}.json) fails to return any bibliographic metadata and silently returns {} instead.

This occurs because the handler get_volumes_multiget in openlibrary/fastapi/books.py uses a custom regex matching block MULTIGET_PATH_RE to manually parse the request path. The regex r"/api/volumes/(brief|full)/json/(.+)" uses (.+) which matches the entire path including the trailing .json extension. This overrides the pre-parsed req argument provided by Starlette, causing readlinks to look up an invalid identifier (e.g. oclc:19683037.json instead of oclc:19683037), returning no results.

Proposed Solution

FastAPI's route matching decorator @router.get("/api/volumes/{brief_or_full}/json/{req}.json") already extracts and unquotes the req parameter without the .json suffix. We can remove the redundant and buggy custom regex matching block in get_volumes_multiget and simply pass the parameter directly to readlinks.readlinks(req, {}).

Additionally, we should update the test suite under TestGetVolumesMultiget in openlibrary/tests/fastapi/test_books.py to assert the arguments passed to the mocked readlinks function to prevent future regressions.

Proposed Changes

diff --git a/openlibrary/fastapi/books.py b/openlibrary/fastapi/books.py
index 3e3233461..0f1707936 100644
--- a/openlibrary/fastapi/books.py
+++ b/openlibrary/fastapi/books.py
@@ -6,8 +6,6 @@ the best practices like Response Models because JSONP makes it quite complicated
 
 from __future__ import annotations
 
-import re
-import urllib.parse
 from typing import Annotated, Any, Literal
 
 import web
@@ -96,9 +94,6 @@ async def get_books(
     return wrap_jsonp(request, result_str)
 
 
-MULTIGET_PATH_RE = re.compile(r"/api/volumes/(brief|full)/json/(.+)")
-
-
 @router.get("/api/volumes/{brief_or_full}/json/{req}", include_in_schema=False)
 @router.get("/api/volumes/{brief_or_full}/json/{req}.json")
 async def get_volumes_multiget(
@@ -117,16 +114,6 @@ async def get_volumes_multiget(
     """
     web.ctx.home = f"{request.url.scheme}://{request.url.netloc}"
 
-    raw_uri = request.url.path
-
-    decoded_path = urllib.parse.unquote(raw_uri)
-
-    m = MULTIGET_PATH_RE.match(decoded_path)
-    if not m or len(m.groups()) != 2:
-        return {}
-
-    _brief_or_full, req = m.groups()
-
     result = await readlinks.readlinks(req, {})
     return wrap_jsonp(request, result)
 
diff --git a/openlibrary/tests/fastapi/test_books.py b/openlibrary/tests/fastapi/test_books.py
index 174c43491..e655a3afb 100644
--- a/openlibrary/tests/fastapi/test_books.py
+++ b/openlibrary/tests/fastapi/test_books.py
@@ -316,7 +316,7 @@ class TestGetVolumesMultiget:
         response = client.get("/api/volumes/brief/json/isbn:0452010586.json")
 
         assert response.status_code == 200
-        mock_readlinks.assert_called_once()
+        mock_readlinks.assert_called_once_with("isbn:0452010586", {})
 
     def test_multiple_identifiers(self, client, mock_readlinks):
         """Verify pipe-separated identifiers are passed through."""

Verification / Testing in Dev

The proposed fix has been tested in the local development environment and works perfectly fine:

  1. Manual curl Verification: Making a local curl request using the .json suffix now correctly returns the full metadata JSON block for oclc:19683037 instead of {}.
  2. Automated test Verification: Running unit tests (docker compose run --rm home pytest openlibrary/tests/fastapi/test_books.py) passes successfully with 100% green status, proving the updated mock_readlinks parameters assertion is correct.

Related Files

  • openlibrary/fastapi/books.py
  • openlibrary/tests/fastapi/test_books.py
  • URL: https://openlibrary.org/api/volumes/brief/json/oclc:19683037.json

Reproducing the bug

  1. Make a curl request to a valid identifier using the .json suffix:
    curl.exe https://openlibrary.org/api/volumes/brief/json/oclc:19683037.json
    
  2. Make the same request without the .json suffix:
    curl.exe https://openlibrary.org/api/volumes/brief/json/oclc:19683037
    
  • Expected behavior: Both requests should return the same bibliographic metadata JSON for oclc:19683037.

  • Actual behavior: The request with the .json suffix returns an empty {} dictionary, while the request without the suffix correctly returns the full metadata JSON block.

Context

  • Browser (Chrome, Safari, Firefox, etc): All
  • OS (Windows, Mac, etc): All
  • Logged in (Y/N): N
  • Environment (prod, dev, local): prod, local

Breakdown

Implementation Details (for maintainers)

Requirements Checklist

  • [ ]

Related files

Stakeholders


Instructions for Contributors

  • Please run these commands to ensure your repository is up to date before creating a new branch to work on this issue and each time after pushing code to Github, because the pre-commit bot may add commits to your PRs upstream.

RsbhThakur avatar Jul 02 '26 09:07 RsbhThakur

Thank you @RsbhThakur for submitting this issue!

⚠️ Contributors, this issue will be ready to work on once:

  • [ ] Triage — maintainers will add Priority: * and Lead: @* to replace Needs: Triage and Needs: Lead

Context

  • Confirmed root cause by reading openlibrary/fastapi/books.py:99-131 directly: MULTIGET_PATH_RE = re.compile(r"/api/volumes/(brief|full)/json/(.+)") re-parses the raw decoded request path instead of using the already-parsed req path parameter that FastAPI/Starlette provides. Because (.+) is greedy, when the request path ends in .json (the second @router.get decorator), the captured req includes the literal .json suffix, so readlinks.readlinks() is called with an invalid identifier and returns no matches — exactly the behavior described.
  • This endpoint was introduced in #11922 ("migrate /api/books and /api/volumes to fastapi", merged 2026-04-09) and touched again by a later "Asyncify /api/books and /api/volumes" commit (2026-04-17). Neither introduced a test that asserts the actual identifier string passed to readlinks, which is why the regression shipped unnoticed.
  • openlibrary/tests/fastapi/test_books.py::TestGetVolumesMultiget currently has three tests (test_calls_readlinks, test_multiple_identifiers, test_jsonp_callback), all of which only assert mock_readlinks.assert_called_once() — call count, not arguments. The diff in this issue strengthens one of the three; the other two carry the same blind spot.
  • No duplicate or related open issue found (searched "volumes multiget", "api/volumes", "MULTIGET_PATH_RE").

Issue Assessment

Action items

  • [ ] Consider opening a PR directly — the proposal already includes a complete, tested diff, so tracking this as an issue-only step is likely redundant
  • [ ] If opening a PR, also strengthen test_multiple_identifiers and test_jsonp_callback to assert the arguments passed to readlinks, not just call count, since they share the same regression risk this issue identifies

Removed Needs: Breakdown — the proposal already contains a complete, tested diff; there isn't further decomposition needed here.

cc @RayBB (fastapi migration lead for this endpoint) — for triage/lead assignment when convenient.

Full triage checklist (maintainers / Richy)
  • [x] Triage — correct labels applied or removed
  • [x] Problem / opportunity — problem is clear, audience identified, actionable
  • [x] Scope — issue is well-scoped; does not try to do too many things
  • [x] Justification — reasoning and impact stated; sufficient for leads to prioritize
  • [x] Success & testing criteria — defines what "done" looks like, verifiable by a contributor
  • [x] Proposal & breakdown — concrete plan present; checklist actionable for a contributor
  • [x] If bug: environment & repro steps — browser, version, local vs prod; steps to reproduce
  • [x] Risks, concerns, open questions — identified and surfaced (any security or privacy implications?)
  • [x] Richy context — relevant code, commits, PRs reviewed; no duplicate issue found
  • [x] References — screenshots, designs, docs, and links present where needed

[!NOTE] This comment was automatically generated by Richy, via PAM, Open Library's Project AI Manager, on behalf of @mekarpeles. Richy is designed to provide status visibility, perform basic project management functions and relevant codebase research, and provide actionable feedback so contributors aren't left waiting.

— Richy, via PAM (Open Library's Project AI Manager)

openlibrary-bot avatar Jul 02 '26 09:07 openlibrary-bot

I've opened PR #13093 that resolves this issue.

The PR applies the fix described in the issue body, and I've also strengthened all three mock assertions in the unit test suite to address the blind spots highlighted by the PAM.

Any advice, feedback, or suggestions from maintainers and contributors are highly welcomed!

RsbhThakur avatar Jul 02 '26 09:07 RsbhThakur

hi is this issue still open? if yes then i would like to work on this. Please tag me if it is open.

TechGenius-Karan avatar Jul 18 '26 12:07 TechGenius-Karan

@TechGenius-Karan This issue is assigned to me and I have already raised a PR, it's awaiting review from @mekarpeles. Thanks!

RsbhThakur avatar Jul 18 '26 12:07 RsbhThakur

Oh ok thank you for updating me

TechGenius-Karan avatar Jul 18 '26 13:07 TechGenius-Karan