Skip to content

add wikidata update capability to the flask api#212

Merged
LizzAlice merged 2 commits intomainfrom
add_wikidata_update
Mar 6, 2026
Merged

add wikidata update capability to the flask api#212
LizzAlice merged 2 commits intomainfrom
add_wikidata_update

Conversation

@LizzAlice
Copy link
Copy Markdown
Contributor

@LizzAlice LizzAlice commented Mar 6, 2026

add wikidata update capability to flask app

Summary by CodeRabbit

  • New Features

    • Added a new POST API endpoint to trigger updates for a single Wikidata identifier (submit qid in JSON).
  • Known Issues

    • The new endpoint may fail to return a valid response in some cases, causing requests to error; a fix is planned.

@LizzAlice LizzAlice requested a review from eloiferrer March 6, 2026 10:46
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 6, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5d5d5760-b610-4622-91e8-4a70f9b2377a

📥 Commits

Reviewing files that changed from the base of the PR and between 87912f9 and 39fd820.

📒 Files selected for processing (1)
  • flask_app/app.py

📝 Walkthrough

Walkthrough

Adds a new POST /update/wikidata endpoint to the Flask app that expects JSON with a qid, instantiates WikidataImporter and calls update_entities(id_list=[qid]). The handler validates qid and contains a bug: it returns an undefined variable (result vs. the assigned name).

Changes

Cohort / File(s) Summary
Wikidata update endpoint
flask_app/app.py
Added import WikidataImporter and new POST /update/wikidata route: validates JSON qid, creates WikidataImporter, calls update_entities(id_list=[qid]), and returns JSON — route returns an undefined variable name (likely bug).

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Flask as FlaskApp
    participant Importer as WikidataImporter
    participant WDAPI as Wikidata API

    Client->>Flask: POST /update/wikidata { "qid": "Q..." }
    Flask->>Flask: validate JSON & extract qid
    Flask->>Importer: new WikidataImporter()
    Flask->>Importer: update_entities(id_list=[qid])
    Importer->>WDAPI: fetch/update entity Q...
    WDAPI-->>Importer: entity data / status
    Importer-->>Flask: update result
    Flask-->>Client: 200 { ...result... }
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • Add flask #177: Adds a separate POST /import/wikidata endpoint that invokes Mardi's Wikidata importer for multiple QIDs — closely related to this new single-qid endpoint.

Suggested reviewers

  • eloiferrer

Poem

🐰 I found a qid on the breeze,
I hopped it in with gentle ease,
One little route, a tiny cheer,
The importer bounds—data near! 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'add wikidata update capability to the flask api' accurately and directly summarizes the main change—introducing a new API endpoint for Wikidata updates in the Flask application.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add_wikidata_update

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
flask_app/app.py (1)

212-217: Docstring is inaccurate.

The docstring says "Update person profile from wikidata" but the update_entities method handles general entities (items and properties), not just person profiles. The return description mentions "an empty list" but update_entities returns either a single MaRDI ID string or a dict of updated entities.

📝 Suggested docstring update
 `@app.post`("/update/wikidata")
 def update_wikidata():
-    """Update person profile from wikidata
+    """Update a Wikidata entity in the local Wikibase.

-    Expects JSON with a ``qid`` field, which should contain the QID of a wikidata item. 
+    Expects JSON with a ``qid`` field containing a Wikidata item or property ID.

     Returns:
-        Response, either the QID that was updated or an empty list
+        Flask response tuple with the updated MaRDI ID or import result.
     """
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@flask_app/app.py` around lines 212 - 217, The docstring for update_entities
is misleading and should be updated: change the summary from “Update person
profile from wikidata” to indicate it updates general Wikidata entities (items
and properties), update the input description to reflect the expected JSON
payload (e.g., a single "qid" or a collection of QIDs as accepted by
update_entities), and correct the return description to state that the function
returns either a single MaRDI ID string for single-entity updates or a dict
mapping QIDs to update results for batch updates; update_entities is the
function to modify.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@flask_app/app.py`:
- Around line 210-225: The update_wikidata view lacks logging, JSON-wrapped
responses, and exception handling: add log.info("Called 'update_wikidata'.") at
the start of update_wikidata, call WikidataImporter() and
wdi.update_entities(id_list=[qid]) inside a try block, wrap the successful
response in jsonify(...) before returning, catch LoginError from
WikidataImporter and return an appropriate auth error (e.g., jsonify(error=...)
with a 401/503 code), catch ValueError from update_entities and return
jsonify(error=...) with 400, and catch a generic Exception to log the exception
and return jsonify(error="internal error") with 500; reference the
functions/classes/names WikidataImporter, update_entities, update_wikidata,
request.get_json, and log.info to locate where to apply these changes.

---

Nitpick comments:
In `@flask_app/app.py`:
- Around line 212-217: The docstring for update_entities is misleading and
should be updated: change the summary from “Update person profile from wikidata”
to indicate it updates general Wikidata entities (items and properties), update
the input description to reflect the expected JSON payload (e.g., a single "qid"
or a collection of QIDs as accepted by update_entities), and correct the return
description to state that the function returns either a single MaRDI ID string
for single-entity updates or a dict mapping QIDs to update results for batch
updates; update_entities is the function to modify.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 80145b66-19d8-4501-a15d-011ab40f2cd5

📥 Commits

Reviewing files that changed from the base of the PR and between 09a81fd and 87912f9.

📒 Files selected for processing (1)
  • flask_app/app.py

Comment thread flask_app/app.py Outdated
Comment on lines +210 to +225
@app.post("/update/wikidata")
def update_wikidata():
"""Update person profile from wikidata

Expects JSON with a ``qid`` field, which should contain the QID of a wikidata item.

Returns:
Response, either the QID that was updated or an empty list
"""
data = request.get_json(silent=True) or {}
qid = data.get("qid")
if not qid:
return jsonify(error="missing qid"), 400
wdi = WikidataImporter()
response = wdi.update_entities(id_list=[qid])
return response, 200
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Missing exception handling will cause unhandled 500 errors.

Based on the relevant code snippets, WikidataImporter() can raise LoginError on authentication failure, and update_entities() can raise ValueError for invalid QID formats (e.g., IDs not starting with 'Q' or 'P'). Other endpoints in this file consistently wrap external calls in try/except blocks.

Additionally:

  • The response should be wrapped in jsonify() for consistency and proper JSON serialization (especially when update_entities returns a string).
  • Missing log.info("Called 'update_wikidata'.") at the start, which other endpoints include.
🔧 Proposed fix with exception handling and JSON serialization
 `@app.post`("/update/wikidata")
 def update_wikidata():
     """Update person profile from wikidata

     Expects JSON with a ``qid`` field, which should contain the QID of a wikidata item. 

     Returns:
         Response, either the QID that was updated or an empty list
     """
+    log.info("Called 'update_wikidata'.")
+
     data = request.get_json(silent=True) or {}
     qid = data.get("qid")
     if not qid:
         return jsonify(error="missing qid"), 400
-    wdi = WikidataImporter()
-    response = wdi.update_entities(id_list=[qid])
-    return response, 200
+
+    try:
+        wdi = WikidataImporter()
+        response = wdi.update_entities(id_list=[qid])
+        return jsonify(result=response), 200
+    except ValueError as exc:
+        log.error("Invalid QID format: %s", exc)
+        return jsonify(error="invalid qid format", details=str(exc)), 400
+    except Exception as exc:
+        log.error("Failed to update wikidata entity: %s", exc, exc_info=True)
+        return jsonify(error="update failed", details=str(exc)), 500
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@flask_app/app.py` around lines 210 - 225, The update_wikidata view lacks
logging, JSON-wrapped responses, and exception handling: add log.info("Called
'update_wikidata'.") at the start of update_wikidata, call WikidataImporter()
and wdi.update_entities(id_list=[qid]) inside a try block, wrap the successful
response in jsonify(...) before returning, catch LoginError from
WikidataImporter and return an appropriate auth error (e.g., jsonify(error=...)
with a 401/503 code), catch ValueError from update_entities and return
jsonify(error=...) with 400, and catch a generic Exception to log the exception
and return jsonify(error="internal error") with 500; reference the
functions/classes/names WikidataImporter, update_entities, update_wikidata,
request.get_json, and log.info to locate where to apply these changes.

@LizzAlice LizzAlice merged commit 2037421 into main Mar 6, 2026
1 of 2 checks passed
@LizzAlice LizzAlice deleted the add_wikidata_update branch March 6, 2026 14:32
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.

2 participants