|
| 1 | +.. _api_search: |
| 2 | + |
| 3 | +API searches |
| 4 | +========================================================== |
| 5 | + |
| 6 | +To run API searches, it is often necessary to represent a query in the form of a URL as opposed to a query string. |
| 7 | +Using the Crossref API as an example, the following illustrates how to construct such a URL to retrieve and store records. |
| 8 | + |
| 9 | +.. code-block:: python |
| 10 | + :linenos: |
| 11 | +
|
| 12 | + import datetime |
| 13 | + from pathlib import Path |
| 14 | + from colrev.packages.crossref.src import crossref_api |
| 15 | + from colrev.writer.write_utils import write_file |
| 16 | + |
| 17 | + from search_query.constants import Fields, Operators |
| 18 | + from search_query.or_query import OrQuery |
| 19 | + from search_query.search_file import SearchFile |
| 20 | + |
| 21 | + def to_crossref_url(query): |
| 22 | + """Translate query into a Crossref-compatible URL.""" |
| 23 | + if query.value != Operators.OR: |
| 24 | + raise ValueError("Crossref serializer only supports OR queries.") |
| 25 | + |
| 26 | + query_parts = [] |
| 27 | + for child in query.children: |
| 28 | + if child.operator: |
| 29 | + raise ValueError("Nested operators are not supported in Crossref serializer.") |
| 30 | + if child.search_field.value != Fields.TITLE: |
| 31 | + raise ValueError(f"Only title field is supported in Crossref serializer ({child.search_field})") |
| 32 | + query_parts.append(child.value.strip()) |
| 33 | + |
| 34 | + # Crossref uses '+' for spaces in query values |
| 35 | + query_string = "+".join(query_parts) |
| 36 | + return f"https://api.crossref.org/works?query.title={query_string}" |
| 37 | + |
| 38 | + if __name__ == "__main__": |
| 39 | + |
| 40 | + query = OrQuery(["microsourcing", "lululemon"], search_field="ti") |
| 41 | + |
| 42 | + url = to_crossref_url(query) |
| 43 | + api_crossref = crossref_api.CrossrefAPI(params={"url": url}) |
| 44 | + records = api_crossref.get_records() |
| 45 | + |
| 46 | + sf = SearchFile( |
| 47 | + search_string=query.to_string(), |
| 48 | + platform="crossref", |
| 49 | + authors=[{"name": "Tom Brady"}], |
| 50 | + record_info={"source": "manual", "url": url}, |
| 51 | + date={"data_entry": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")}, |
| 52 | + search_field="title", |
| 53 | + description="Search for work authored by Tom Brady", |
| 54 | + tags=["microsourcing", "lululemon", "research"] |
| 55 | + ) |
| 56 | + |
| 57 | + sf.save("test/tom_brady_search.json") |
| 58 | + |
| 59 | + records_dict = {record.get_value("doi"): record.get_data() for record in records} |
| 60 | + write_file(records_dict=records_dict, filename=Path("test/crossref_records.bib")) |
| 61 | +
|
0 commit comments