Skip to content

Instantly share code, notes, and snippets.

@paultopia
Created April 4, 2020 21:18
Show Gist options
  • Select an option

  • Save paultopia/ae28e4cb636717ee982e38db60318020 to your computer and use it in GitHub Desktop.

Select an option

Save paultopia/ae28e4cb636717ee982e38db60318020 to your computer and use it in GitHub Desktop.

Revisions

  1. paultopia created this gist Apr 4, 2020.
    52 changes: 52 additions & 0 deletions zotero_add.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    import requests
    import json
    import os
    from copy import deepcopy
    APIKEY = os.environ["ZOTEROKEY"]
    ACCOUNT = os.environ["ZOTEROACCOUNT"]
    TESTITEM = '10.2307/4486062' # just the same example item used on https://github.com/zotero/translation-server

    def get_item_from_identifier(identifier):
    endpoint = "http://zotglitch.glitch.me/search"
    headers = {'Content-Type': 'text/plain'}
    resp = requests.post(endpoint, data=identifier, headers=headers)
    return resp.json()

    def get_item_template(itemType):
    endpoint = "https://api.zotero.org/items/new"
    params = {"itemType": itemType}
    resp = requests.get(endpoint, params=params)
    return resp.json()

    def correct_keys(item, template):
    itemcopy = deepcopy(item)
    correct_keys = set(template.keys())
    item_keys = set(item.keys())
    bad_keys = item_keys - correct_keys
    for key in bad_keys:
    itemcopy.pop(key, None)
    itemcopy['tags'] = []
    itemcopy['relations'] = []
    itemcopy['collections'] = []
    return itemcopy

    def make_zotero_item_from_identifier(identifier):
    item = get_item_from_identifier(identifier)[0]
    itemType = item["itemType"]
    template = get_item_template(itemType)
    return correct_keys(item, template)

    def create_zotero_item(item):
    endpoint = f'https://api.zotero.org/users/{ACCOUNT}/items'
    headers = {"Zotero-API-Key": APIKEY}
    data = [item]
    resp = requests.post(endpoint, headers=headers, json=data)
    print(resp.status_code)
    return resp.json()


    if __name__ == '__main__':
    item = make_zotero_item_from_identifier(TESTITEM)
    attempt = create_zotero_item(item)
    print(attempt)