references/write-api.md
5.6 KB查看排版效果| 1 | # Write API Methods |
| 2 | |
| 3 | ## Creating Items |
| 4 | |
| 5 | For the remote API, use `item_template()` to get a valid template. The local API lacks `/items/new`; build data from the type/field endpoints instead (see [authentication.md](authentication.md)). All write examples below are illustrative and must use an authorized target library. |
| 6 | |
| 7 | ```python |
| 8 | # Get a template for a specific item type |
| 9 | template = zot.item_template('journalArticle') |
| 10 | |
| 11 | # Fill in fields |
| 12 | template['title'] = 'Example article (illustrative metadata)' |
| 13 | template['date'] = '2024' |
| 14 | # Populate DOI, title, journal, and authors together from a verified source; |
| 15 | # never pair a real DOI with fabricated bibliographic metadata. |
| 16 | template['creators'] = [ |
| 17 | {'creatorType': 'author', 'firstName': 'Jane', 'lastName': 'Doe'}, |
| 18 | {'creatorType': 'author', 'firstName': 'John', 'lastName': 'Smith'}, |
| 19 | ] |
| 20 | |
| 21 | # Validate fields before creating (raises InvalidItemFieldsError if invalid) |
| 22 | zot.check_items([template]) |
| 23 | |
| 24 | # Create the item |
| 25 | resp = zot.create_items([template]) |
| 26 | # Response maps are indexed by each input's string index: '0', '1', ... |
| 27 | if resp.get('failed'): |
| 28 | raise RuntimeError(f"Creation failures: {resp['failed']}") |
| 29 | new_key = resp['successful']['0']['key'] |
| 30 | # successful holds saved objects; legacy success maps indices to keys. |
| 31 | # unchanged maps indices to existing keys when no change was needed. |
| 32 | ``` |
| 33 | |
| 34 | ### Create Multiple Items at Once |
| 35 | |
| 36 | ```python |
| 37 | templates = [] |
| 38 | for data in paper_data_list: |
| 39 | t = zot.item_template('journalArticle') |
| 40 | t['title'] = data['title'] |
| 41 | t['DOI'] = data['doi'] |
| 42 | templates.append(t) |
| 43 | |
| 44 | for start in range(0, len(templates), 50): |
| 45 | resp = zot.create_items(templates[start:start + 50]) |
| 46 | if resp.get('failed'): |
| 47 | raise RuntimeError(f"Batch starting at {start}: {resp['failed']}") |
| 48 | ``` |
| 49 | |
| 50 | ### Create Child Items |
| 51 | |
| 52 | ```python |
| 53 | # Create a note as a child of an existing item |
| 54 | note_template = zot.item_template('note') |
| 55 | note_template['note'] = '<p>My annotation here</p>' |
| 56 | zot.create_items([note_template], parentid='PARENTKEY') |
| 57 | ``` |
| 58 | |
| 59 | ## Updating Items |
| 60 | |
| 61 | ```python |
| 62 | # Retrieve, modify, update |
| 63 | item = zot.item('ITEMKEY') |
| 64 | item['data']['title'] = 'Updated Title' |
| 65 | item['data']['abstractNote'] = 'New abstract text.' |
| 66 | success = zot.update_item(item) # returns True or raises error |
| 67 | |
| 68 | # Update many existing items while retaining per-item status |
| 69 | items = zot.items(itemType='journalArticle', limit=10) |
| 70 | for item in items: |
| 71 | item['data']['extra'] = item['data'].get('extra', '') + '\nProcessed' |
| 72 | for start in range(0, len(items), 50): |
| 73 | result = zot.create_items([i['data'] for i in items[start:start + 50]]) |
| 74 | if result.get('failed'): |
| 75 | raise RuntimeError(result['failed']) |
| 76 | ``` |
| 77 | |
| 78 | ## Deleting Items |
| 79 | |
| 80 | ```python |
| 81 | # Permanent deletion of one item: use its object version |
| 82 | item = zot.item('ITEMKEY') |
| 83 | zot.delete_item(item) |
| 84 | |
| 85 | # Multiple deletion uses a LIBRARY version, not the first item's version. |
| 86 | # Review the exact selected keys first; at most 50 per request. |
| 87 | items = zot.items(tag='to-delete', limit=50) |
| 88 | library_version = int(zot.request.headers['Last-Modified-Version']) |
| 89 | if items: |
| 90 | zot.delete_item(items, last_modified=library_version) |
| 91 | |
| 92 | # To trash instead of permanently delete: |
| 93 | item = zot.item('ITEMKEY') |
| 94 | item['data']['deleted'] = 1 # use 0 to restore |
| 95 | zot.update_item(item['data']) |
| 96 | ``` |
| 97 | |
| 98 | ## Item Types and Fields |
| 99 | |
| 100 | ```python |
| 101 | # All available item types |
| 102 | item_types = zot.item_types() |
| 103 | # [{'itemType': 'artwork', 'localized': 'Artwork'}, ...] |
| 104 | |
| 105 | # All available fields |
| 106 | fields = zot.item_fields() |
| 107 | |
| 108 | # Valid fields for a specific item type |
| 109 | journal_fields = zot.item_type_fields('journalArticle') |
| 110 | |
| 111 | # Valid creator types for an item type |
| 112 | creator_types = zot.item_creator_types('journalArticle') |
| 113 | # [{'creatorType': 'author', 'localized': 'Author'}, ...] |
| 114 | |
| 115 | # All localised creator field names |
| 116 | creator_fields = zot.creator_fields() |
| 117 | |
| 118 | # Attachment link modes (needed for attachment templates) |
| 119 | link_modes = zot.item_attachment_link_modes() |
| 120 | |
| 121 | # Template for an attachment |
| 122 | attach_template = zot.item_template('attachment', linkmode='imported_file') |
| 123 | ``` |
| 124 | |
| 125 | ## Optimistic Locking |
| 126 | |
| 127 | Single-item `last_modified` is the **item version**. The normal read/modify/write example already sends it; an explicit override must come from that same item's read: |
| 128 | |
| 129 | ```python |
| 130 | # Only update if this item's version still matches |
| 131 | zot.update_item(item, last_modified=item['version']) |
| 132 | # Raises PreConditionFailedError on a stale version. |
| 133 | ``` |
| 134 | |
| 135 | ## Notes |
| 136 | |
| 137 | - `create_items()` accepts up to 50 items per call; batch if needed. |
| 138 | - `update_items()` auto-chunks at 50 but returns a coarse Boolean without checking each `failed` mapping in 1.15.2. Use `create_items()` with keyed, versioned data in explicit batches when every result must be reconciled. |
| 139 | - If a dict passed to `create_items()` contains a `key` matching an existing item, it will be updated rather than created. |
| 140 | - `check_items()` checks field names against the global field set, not all type-specific values or scientific metadata. Server failures remain possible. |
| 141 | - Item `PATCH` leaves omitted fields unchanged, but supplied arrays replace entire creator/tag/collection lists. Re-fetch after writes before further edits. |
| 142 | - A timeout does not establish whether a write happened. Pyzotero generates a new write token on another `create_items()` call, so blindly repeating an unkeyed create can duplicate records. Reconcile first; retry only verified failures. |
| 143 | - Batch POST preconditions use the library version when supplied; per-object `version` values are usually simpler. HTTP 200 can still contain failed entries. |
| 144 | |
| 145 | Sources: [write request/response contracts](https://www.zotero.org/support/dev/web_api/v3/write_requests), [Pyzotero 1.15.2 source](https://github.com/urschrei/pyzotero/blob/v1.15.2/src/pyzotero/_client.py). |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

