Skip to content

bookops_worldcat.metadata_api

This module provides MetadataSession class for requests to WorldCat Metadata API.

MetadataSession

MetadataSession(
    authorization: Type[WorldcatAccessToken],
    agent: str = None,
    timeout: Union[
        int, float, Tuple[int, int], Tuple[float, float]
    ] = None,
)

Bases: WorldcatSession

OCLC Metadata API wrapper session. Inherits requests.Session methods

agent:                  "User-agent" parameter to be passed in the request
                        header; usage strongly encouraged
timeout:                how long to wait for server to send data before
                        giving up; default value is 3 seconds
Source code in bookops_worldcat\metadata_api.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def __init__(
    self,
    authorization: Type[WorldcatAccessToken],
    agent: str = None,
    timeout: Union[int, float, Tuple[int, int], Tuple[float, float]] = None,
):
    """
    Args:
        authorization:          WorlcatAccessToken object
        agent:                  "User-agent" parameter to be passed in the request
                                header; usage strongly encouraged
        timeout:                how long to wait for server to send data before
                                giving up; default value is 3 seconds
    """
    WorldcatSession.__init__(self, agent=agent, timeout=timeout)

    self.authorization = authorization

    if type(self.authorization).__name__ != "WorldcatAccessToken":
        raise WorldcatSessionError(
            "Argument 'authorization' must include 'WorldcatAccessToken' obj."
        )

    self._update_authorization()

get_brief_bib

get_brief_bib(
    oclcNumber: Union[int, str], hooks: Dict = None
)

Retrieve specific brief bibliographic resource.

Parameters:

Name Type Description Default
oclcNumber Union[int, str]

OCLC bibliographic record number; can be an integer, or string that can include OCLC # prefix

required
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns: requests.Response object

Source code in bookops_worldcat\metadata_api.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def get_brief_bib(self, oclcNumber: Union[int, str], hooks: Dict = None):
    """
    Retrieve specific brief bibliographic resource.

    Args:
        oclcNumber:             OCLC bibliographic record number; can be
                                an integer, or string that can include
                                OCLC # prefix
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks
    Returns:
        `requests.Response` object
    """

    try:
        oclcNumber = verify_oclc_number(oclcNumber)
    except InvalidOclcNumber:
        raise WorldcatSessionError("Invalid OCLC # was passed as an argument")

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    header = {"Accept": "application/json"}
    url = self._url_brief_bib_oclc_number(oclcNumber)

    # send request
    try:
        response = self.get(url, headers=header, hooks=hooks)
        if response.status_code == requests.codes.ok:
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

get_full_bib

get_full_bib(
    oclcNumber: Union[int, str],
    response_format: str = None,
    hooks: Dict = None,
)

Send a GET request for a full bibliographic resource.

Parameters:

Name Type Description Default
oclcNumber Union[int, str]

OCLC bibliographic record number; can be an integer, or string with or without OCLC # prefix

required
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns: requests.Response object

Source code in bookops_worldcat\metadata_api.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def get_full_bib(
    self,
    oclcNumber: Union[int, str],
    response_format: str = None,
    hooks: Dict = None,
):
    """
    Send a GET request for a full bibliographic resource.

    Args:
        oclcNumber:             OCLC bibliographic record number; can be an
                                integer, or string with or without OCLC # prefix
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks
    Returns:
        `requests.Response` object
    """
    try:
        oclcNumber = verify_oclc_number(oclcNumber)
    except InvalidOclcNumber:
        raise WorldcatSessionError("Invalid OCLC # was passed as an argument.")

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    url = self._url_bib_oclc_number(oclcNumber)
    if not response_format:
        response_format = (
            'application/atom+xml;content="application/vnd.oclc.marc21+xml"'
        )
    header = {"Accept": response_format}

    # send request
    try:
        response = self.get(url, headers=header, hooks=hooks)
        if response.status_code == requests.codes.ok:
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

holding_get_status

holding_get_status(
    oclcNumber: Union[int, str],
    inst: str = None,
    instSymbol: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
)

Retrieves Worlcat holdings status of a record with provided OCLC number. The service automatically recognizes institution based on the issued access token.

Parameters:

Name Type Description Default
oclcNumber Union[int, str]

OCLC bibliographic record number; can be an integer, or string with or without OCLC # prefix

required
inst str

registry ID of the institution whose holdings are being checked

None
instSymbol str

optional; OCLC symbol of the institution whose holdings are being checked

None
response_format str

'application/atom+json' (default) or 'application/atom+xml'

'application/atom+json'
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns:

Type Description

requests.Response object

Source code in bookops_worldcat\metadata_api.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
def holding_get_status(
    self,
    oclcNumber: Union[int, str],
    inst: str = None,
    instSymbol: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
):
    """
    Retrieves Worlcat holdings status of a record with provided OCLC number.
    The service automatically recognizes institution based on the issued access
    token.

    Args:
        oclcNumber:             OCLC bibliographic record number; can be an
                                integer, or string with or without OCLC # prefix
        inst:                   registry ID of the institution whose holdings
                                are being checked
        instSymbol:             optional; OCLC symbol of the institution whose
                                holdings are being checked
        response_format:        'application/atom+json' (default) or
                                'application/atom+xml'
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

    Returns:
        `requests.Response` object
    """
    try:
        oclcNumber = verify_oclc_number(oclcNumber)
    except InvalidOclcNumber as exc:
        raise WorldcatSessionError(exc)

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    url = self._url_bib_holdings_check()
    header = {"Accept": response_format}
    payload = {"oclcNumber": oclcNumber, "inst": inst, "instSymbol": instSymbol}

    # send request
    try:
        response = self.get(url, headers=header, params=payload, hooks=hooks)
        if response.status_code == requests.codes.ok:
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

holding_set

holding_set(
    oclcNumber: Union[int, str],
    inst: str = None,
    instSymbol: str = None,
    holdingLibraryCode: str = None,
    classificationScheme: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
)

Sets institution's Worldcat holding on an individual record.

Parameters:

Name Type Description Default
oclcNumber Union[int, str]

OCLC bibliographic record number; can be an integer, or string with or without OCLC # prefix

required
inst str

registry ID of the institution whose holdings are being checked

None
instSymbol str

optional; OCLC symbol of the institution whose holdings are being checked

None
holdingLibraryCode str

four letter holding code to et the holing on

None
classificationScheme str

whether or not to return group availability information

None
response_format str

'application/atom+json' (default) or 'application/atom+xml'

'application/atom+json'
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns:

Type Description

requests.Response object

Source code in bookops_worldcat\metadata_api.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def holding_set(
    self,
    oclcNumber: Union[int, str],
    inst: str = None,
    instSymbol: str = None,
    holdingLibraryCode: str = None,
    classificationScheme: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
):
    """
    Sets institution's Worldcat holding on an individual record.

    Args:
        oclcNumber:             OCLC bibliographic record number; can be an
                                integer, or string with or without OCLC # prefix
        inst:                   registry ID of the institution whose holdings
                                are being checked
        instSymbol:             optional; OCLC symbol of the institution whose
                                holdings are being checked
        holdingLibraryCode:     four letter holding code to et the holing on
        classificationScheme:   whether or not to return group availability
                                information
        response_format:        'application/atom+json' (default) or
                                'application/atom+xml'
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

    Returns:
        `requests.Response` object
    """

    try:
        oclcNumber = verify_oclc_number(oclcNumber)
    except InvalidOclcNumber as exc:
        raise WorldcatSessionError(exc)

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    url = self._url_bib_holdings_action()
    header = {"Accept": response_format}
    payload = {
        "oclcNumber": oclcNumber,
        "inst": inst,
        "instSymbol": instSymbol,
        "holdingLibraryCode": holdingLibraryCode,
        "classificationScheme": classificationScheme,
    }

    # send request
    try:
        response = self.post(url, headers=header, params=payload, hooks=hooks)
        if response.status_code == 201:
            # the service does not return any meaningful response
            # when holdings are succesfully set
            return response
        elif response.status_code == 409:
            # holdings already set
            # it seems resonable to simply ignore this response
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

holding_unset

holding_unset(
    oclcNumber: Union[int, str],
    cascade: Union[int, str] = "0",
    inst: str = None,
    instSymbol: str = None,
    holdingLibraryCode: str = None,
    classificationScheme: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
)

Deletes institution's Worldcat holding on an individual record.

Parameters:

Name Type Description Default
oclcNumber Union[int, str]

OCLC bibliographic record number; can be an integer, or string with or without OCLC # prefix if str the numbers must be separated by comma

required
cascade Union[int, str]

0 or 1, default 0; 0 - don't remove holdings if local holding record or local bibliographic records exists; 1 - remove holding and delete local holdings record and local bibliographic record

'0'
inst str

registry ID of the institution whose holdings are being checked

None
instSymbol str

optional; OCLC symbol of the institution whose holdings are being checked

None
holdingLibraryCode str

four letter holding code to et the holing on

None
classificationScheme str

whether or not to return group availability information

None
response_format str

'application/atom+json' (default) or 'application/atom+xml'

'application/atom+json'
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns:

Type Description

requests.Response object

Source code in bookops_worldcat\metadata_api.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def holding_unset(
    self,
    oclcNumber: Union[int, str],
    cascade: Union[int, str] = "0",
    inst: str = None,
    instSymbol: str = None,
    holdingLibraryCode: str = None,
    classificationScheme: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
):
    """
    Deletes institution's Worldcat holding on an individual record.

    Args:
        oclcNumber:             OCLC bibliographic record number; can be an
                                integer, or string with or without OCLC # prefix
                                if str the numbers must be separated by comma
        cascade:                0 or 1, default 0;
                                0 - don't remove holdings if local holding
                                record or local bibliographic records exists;
                                1 - remove holding and delete local holdings
                                record and local bibliographic record
        inst:                   registry ID of the institution whose holdings
                                are being checked
        instSymbol:             optional; OCLC symbol of the institution whose
                                holdings are being checked
        holdingLibraryCode:     four letter holding code to et the holing on
        classificationScheme:   whether or not to return group availability
                                information
        response_format:        'application/atom+json' (default) or
                                'application/atom+xml'
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

    Returns:
        `requests.Response` object
    """

    try:
        oclcNumber = verify_oclc_number(oclcNumber)
    except InvalidOclcNumber as exc:
        raise WorldcatSessionError(exc)

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    url = self._url_bib_holdings_action()
    header = {"Accept": response_format}
    payload = {
        "oclcNumber": oclcNumber,
        "cascade": cascade,
        "inst": inst,
        "instSymbol": instSymbol,
        "holdingLibraryCode": holdingLibraryCode,
        "classificationScheme": classificationScheme,
    }

    # send request
    try:
        response = self.delete(url, headers=header, params=payload, hooks=hooks)
        if response.status_code == requests.codes.ok:
            # the service does not return any meaningful response
            # when holdings are succesfully deleted
            return response
        elif response.status_code == 409:
            # holdings already set
            # it seems resonable to simply ignore this response
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

holdings_set

holdings_set(
    oclcNumbers: Union[str, List],
    inst: str = None,
    instSymbol: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
)

Set institution holdings for multiple OClC numbers

Parameters:

Name Type Description Default
oclcNumbers Union[str, List]

list of OCLC control numbers for which holdings should be set; they can be integers or strings with or without OCLC # prefix; if str the numbers must be separated by comma

required
inst str

registry ID of the institution whose holdings are being checked

None
instSymbol str

optional; OCLC symbol of the institution whose holdings are being checked

None
response_format str

'application/atom+json' (default) or 'application/atom+xml'

'application/atom+json'
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns: requests.Response object

Source code in bookops_worldcat\metadata_api.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
def holdings_set(
    self,
    oclcNumbers: Union[str, List],
    inst: str = None,
    instSymbol: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
):
    """
    Set institution holdings for multiple OClC numbers

    Args:
        oclcNumbers:            list of OCLC control numbers for which holdings
                                should be set;
                                they can be integers or strings with or
                                without OCLC # prefix;
                                if str the numbers must be separated by comma
        inst:                   registry ID of the institution whose holdings
                                are being checked
        instSymbol:             optional; OCLC symbol of the institution whose
                                holdings are being checked
        response_format:        'application/atom+json' (default) or
                                'application/atom+xml'
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks
    Returns:
        `requests.Response` object
    """
    responses = []

    try:
        vetted_numbers = verify_oclc_numbers(oclcNumbers)
    except InvalidOclcNumber as exc:
        raise WorldcatSessionError(exc)

    url = self._url_bib_holdings_batch_action()
    header = {"Accept": response_format}

    # split into batches of 50 and issue request for each batch
    for batch in self._split_into_legal_volume(vetted_numbers):
        payload = {
            "oclcNumbers": batch,
            "inst": inst,
            "instSymbol": instSymbol,
        }

        # make sure access token is still valid and if not request a new one
        if self.authorization.is_expired():
            self._get_new_access_token()

        # send request
        try:
            response = self.post(url, headers=header, params=payload, hooks=hooks)

            if response.status_code == 207:
                # the service returns multi-status response
                responses.append(response)
            else:
                error_msg = _parse_error_response(response)
                raise WorldcatRequestError(error_msg)
        except WorldcatRequestError as exc:
            raise WorldcatSessionError(exc)
        except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
            raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
        except:
            raise WorldcatSessionError(
                f"Unexpected request error: {sys.exc_info()[0]}"
            )
    return responses

holdings_unset

holdings_unset(
    oclcNumbers: Union[str, List],
    cascade: Union[int, str] = "0",
    inst: str = None,
    instSymbol: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
)

Set institution holdings for multiple OClC numbers

Parameters:

Name Type Description Default
oclcNumbers Union[str, List]

list of OCLC control numbers for which holdings should be set; they can be integers or strings with or without OCLC # prefix; if str the numbers must be separated by comma

required
cascade Union[int, str]

0 or 1, default 0; 0 - don't remove holdings if local holding record or local bibliographic records exists; 1 - remove holding and delete local holdings record and local bibliographic record

'0'
inst str

registry ID of the institution whose holdings are being checked

None
instSymbol str

optional; OCLC symbol of the institution whose holdings are being checked

None
response_format str

'application/atom+json' (default) or 'application/atom+xml'

'application/atom+json'
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns: requests.Response object

Source code in bookops_worldcat\metadata_api.py
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
def holdings_unset(
    self,
    oclcNumbers: Union[str, List],
    cascade: Union[int, str] = "0",
    inst: str = None,
    instSymbol: str = None,
    response_format: str = "application/atom+json",
    hooks: Dict = None,
):
    """
    Set institution holdings for multiple OClC numbers

    Args:
        oclcNumbers:            list of OCLC control numbers for which holdings
                                should be set;
                                they can be integers or strings with or
                                without OCLC # prefix;
                                if str the numbers must be separated by comma
        cascade:                0 or 1, default 0;
                                0 - don't remove holdings if local holding
                                record or local bibliographic records exists;
                                1 - remove holding and delete local holdings
                                record and local bibliographic record
        inst:                   registry ID of the institution whose holdings
                                are being checked
        instSymbol:             optional; OCLC symbol of the institution whose
                                holdings are being checked
        response_format:        'application/atom+json' (default) or
                                'application/atom+xml'
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks
    Returns:
        `requests.Response` object
    """
    responses = []

    try:
        vetted_numbers = verify_oclc_numbers(oclcNumbers)
    except InvalidOclcNumber as exc:
        raise WorldcatSessionError(exc)

    url = self._url_bib_holdings_batch_action()
    header = {"Accept": response_format}

    # split into batches of 50 and issue request for each batch
    for batch in self._split_into_legal_volume(vetted_numbers):
        payload = {
            "oclcNumbers": batch,
            "cascade": cascade,
            "inst": inst,
            "instSymbol": instSymbol,
        }

        # make sure access token is still valid and if not request a new one
        if self.authorization.is_expired():
            self._get_new_access_token()

        # send request
        try:
            response = self.delete(url, headers=header, params=payload, hooks=hooks)

            if response.status_code == 207:
                # the service returns multi-status response
                responses.append(response)
            else:
                error_msg = _parse_error_response(response)
                raise WorldcatRequestError(error_msg)
        except WorldcatRequestError as exc:
            raise WorldcatSessionError(exc)
        except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
            raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
        except:
            raise WorldcatSessionError(
                f"Unexpected request error: {sys.exc_info()[0]}"
            )
    return responses

search_brief_bib_other_editions

search_brief_bib_other_editions(
    oclcNumber: Union[int, str],
    offset: int = None,
    limit: int = None,
    hooks: Dict = None,
)

Retrieve other editions related to bibliographic resource with provided OCLC #.

Parameters:

Name Type Description Default
oclcNumber Union[int, str]

OCLC bibliographic record number; can be an integer, or string with or without OCLC # prefix

required
offset int

start position of bibliographic records to return; default 1

None
limit int

maximum nuber of records to return; maximum 50, default 10

None
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns: requests.Response object

Source code in bookops_worldcat\metadata_api.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
def search_brief_bib_other_editions(
    self,
    oclcNumber: Union[int, str],
    offset: int = None,
    limit: int = None,
    hooks: Dict = None,
):
    """
    Retrieve other editions related to bibliographic resource with provided
    OCLC #.

    Args:
        oclcNumber:             OCLC bibliographic record number; can be an
                                integer, or string with or without OCLC # prefix
        offset:                 start position of bibliographic records to
                                return; default 1
        limit:                  maximum nuber of records to return;
                                maximum 50, default 10
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks
    Returns:
        `requests.Response` object
    """
    try:
        oclcNumber = verify_oclc_number(oclcNumber)
    except InvalidOclcNumber:
        raise WorldcatSessionError("Invalid OCLC # was passed as an argument")

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    url = self._url_brief_bib_other_editions(oclcNumber)
    header = {"Accept": "application/json"}
    payload = {"offset": offset, "limit": limit}

    # send request
    try:
        response = self.get(url, headers=header, params=payload, hooks=hooks)
        if response.status_code == requests.codes.ok:
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

search_brief_bibs

search_brief_bibs(
    q: str,
    deweyNumber: str = None,
    datePublished: str = None,
    heldBy: str = None,
    heldByGroup: str = None,
    inLanguage: str = None,
    inCatalogLanguage: str = "eng",
    materialType: str = None,
    catalogSource: str = None,
    itemType: str = None,
    itemSubType: str = None,
    retentionCommitments: bool = None,
    spProgram: str = None,
    facets: str = None,
    groupRelatedEditions: str = None,
    orderBy: str = "mostWidelyHeld",
    offset: int = None,
    limit: int = None,
    hooks: Dict = None,
)

Send a GET request for brief bibliographic resources.

Parameters:

Name Type Description Default
q str

query in the form of a keyword search or fielded search; examples: ti:Zendegi ti:"Czarne oceany" bn:9781680502404 kw:python databases ti:Zendegi AND au:greg egan (au:Okken OR au:Myers) AND su:python

required
deweyNumber str

limits the response to the specified dewey classification number(s); for multiple values repeat the parameter, example: '794,180'

None
datePublished str

restricts the response to one or more dates, or to a range, examples: '2000' '2000-2005' '2000,2005'

None
heldBy str

institution symbol; restricts to records held by indicated institution

None
heldByGroup str

restricts to holdings held by group symbol

None
inLanguage str

restrics the response to the single specified language, example: 'fre'

None
inCataloglanguage

restrics the response to specified cataloging language, example: 'eng'; default 'eng'

required
materialType str

restricts responses to specified material type, example: 'bks', 'vis'

None
catalogSource str

restrict to responses to single OCLC symbol as the cataloging source, example: 'DLC'

None
itemType str

restricts reponses to single specified OCLC top-level facet type, example: 'book'

None
itemSubType str

restricts responses to single specified OCLC sub facet type, example: 'digital'

None
retentionCommitments bool

restricts responses to bibliographic records with retention commitment; True or False

None
spProgram str

restricts responses to bibliographic records associated with particular shared print program

None
facets str

list of facets to restrict responses

None
groupRelatedEditions str

whether or not use FRBR grouping, options: 'Y' (yes) or 'N' (no); server's default 'N'

None
orderBy str

results sort key; options: 'recency' 'bestMatch' 'creator' 'publicationDateAsc' 'publicationDateDesc' 'mostWidelyHeld' 'title'

'mostWidelyHeld'
offset int

start position of bibliographic records to return; default 1

None
limit int

maximum nuber of records to return; maximum 50, default 10

None
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns:

Type Description

requests.Response object

Source code in bookops_worldcat\metadata_api.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
def search_brief_bibs(
    self,
    q: str,
    deweyNumber: str = None,
    datePublished: str = None,
    heldBy: str = None,
    heldByGroup: str = None,
    inLanguage: str = None,
    inCatalogLanguage: str = "eng",
    materialType: str = None,
    catalogSource: str = None,
    itemType: str = None,
    itemSubType: str = None,
    retentionCommitments: bool = None,
    spProgram: str = None,
    facets: str = None,
    groupRelatedEditions: str = None,
    orderBy: str = "mostWidelyHeld",
    offset: int = None,
    limit: int = None,
    hooks: Dict = None,
):
    """
    Send a GET request for brief bibliographic resources.

    Args:
        q:                      query in the form of a keyword search or
                                fielded search;
                                examples:
                                    ti:Zendegi
                                    ti:"Czarne oceany"
                                    bn:9781680502404
                                    kw:python databases
                                    ti:Zendegi AND au:greg egan
                                    (au:Okken OR au:Myers) AND su:python
        deweyNumber:            limits the response to the
                                specified dewey classification number(s);
                                for multiple values repeat the parameter,
                                example:
                                    '794,180'
        datePublished:          restricts the response to one or
                                more dates, or to a range,
                                examples:
                                    '2000'
                                    '2000-2005'
                                    '2000,2005'
        heldBy:                 institution symbol; restricts to records
                                held by indicated institution
        heldByGroup:            restricts to holdings held by group symbol
        inLanguage:             restrics the response to the single
                                specified language, example: 'fre'
        inCataloglanguage:      restrics the response to specified
                                cataloging language, example: 'eng';
                                default 'eng'
        materialType:           restricts responses to specified material type,
                                example: 'bks', 'vis'
        catalogSource:          restrict to responses to single OCLC symbol as
                                the cataloging source, example: 'DLC'
        itemType:               restricts reponses to single specified OCLC
                                top-level facet type, example: 'book'
        itemSubType:            restricts responses to single specified OCLC
                                sub facet type, example: 'digital'
        retentionCommitments:   restricts responses to bibliographic records
                                with retention commitment; True or False
        spProgram:              restricts responses to bibliographic records
                                associated with particular shared print
                                program
        facets:                 list of facets to restrict responses
        groupRelatedEditions:   whether or not use FRBR grouping,
                                options: 'Y' (yes) or 'N' (no);
                                server's default 'N'
        orderBy:                results sort key;
                                options:
                                    'recency'
                                    'bestMatch'
                                    'creator'
                                    'publicationDateAsc'
                                    'publicationDateDesc'
                                    'mostWidelyHeld'
                                    'title'
        offset:                 start position of bibliographic records to
                                return; default 1
        limit:                  maximum nuber of records to return;
                                maximum 50, default 10
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

    Returns:
        `requests.Response` object

    """
    if not q:
        raise WorldcatSessionError("Argument 'q' is requried to construct query.")

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    url = self._url_brief_bib_search()
    header = {"Accept": "application/json"}
    payload = {
        "q": q,
        "deweyNumber": deweyNumber,
        "datePublished": datePublished,
        "heldBy": heldBy,
        "heldByGroup": heldByGroup,
        "inLanguage": inLanguage,
        "inCatalogLanguage": inCatalogLanguage,
        "materialType": materialType,
        "catalogSource": catalogSource,
        "itemType": itemType,
        "itemSubType": itemSubType,
        "retentionCommitments": retentionCommitments,
        "spProgram": spProgram,
        "facets": facets,
        "groupRelatedEditions": groupRelatedEditions,
        "orderBy": orderBy,
        "offset": offset,
        "limit": limit,
    }

    # send request
    try:
        response = self.get(url, headers=header, params=payload, hooks=hooks)
        if response.status_code == requests.codes.ok:
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatRequestError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

search_current_control_numbers

search_current_control_numbers(
    oclcNumbers: Union[int, str],
    response_format: str = "application/atom+json",
    hooks: Dict = None,
)

Retrieve current OCLC control numbers

Parameters:

Name Type Description Default
oclcNumbers Union[int, str]

list of OCLC control numbers to be checked; they can be integers or strings with or without OCLC # prefix; if str the numbers must be separated by comma

required
response_format str

'application/atom+json' (default) or 'application/atom+xml'

'application/atom+json'
hooks Dict

Requests library hook system that can be used for singnal event handling, see more at: https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

None

Returns:

Type Description

requests.Response object

Source code in bookops_worldcat\metadata_api.py
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
def search_current_control_numbers(
    self,
    oclcNumbers: Union[int, str],
    response_format: str = "application/atom+json",
    hooks: Dict = None,
):
    """
    Retrieve current OCLC control numbers

    Args:
        oclcNumbers:            list of OCLC control numbers to be checked;
                                they can be integers or strings with or
                                without OCLC # prefix;
                                if str the numbers must be separated by comma
        response_format:        'application/atom+json' (default) or
                                'application/atom+xml'
        hooks:                  Requests library hook system that can be
                                used for singnal event handling, see more at:
                                https://requests.readthedocs.io/en/master/user/advanced/#event-hooks

    Returns:
        `requests.Response` object
    """

    try:
        vetted_numbers = verify_oclc_numbers(oclcNumbers)
    except InvalidOclcNumber as exc:
        raise WorldcatSessionError(exc)

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    header = {"Accept": response_format}
    url = self._url_bib_check_oclc_numbers()
    payload = {"oclcNumbers": ",".join(vetted_numbers)}

    # send request
    try:
        response = self.get(url, headers=header, params=payload, hooks=hooks)
        if response.status_code == 207:  # multi-status response
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

search_general_holdings

search_general_holdings(
    oclcNumber: Union[int, str] = None,
    isbn: str = None,
    issn: str = None,
    holdingsAllEditions: bool = None,
    heldInCountry: str = None,
    heldByGroup: str = None,
    heldBy: str = None,
    lat: float = None,
    lon: float = None,
    distance: int = None,
    unit: str = None,
    offset: int = None,
    limit: int = None,
    hooks: Dict = None,
)

Given a known item gets summary of holdings.

Parameters:

Name Type Description Default
oclcNumber Union[int, str]

OCLC bibliographic record number; can be an integer, or string that can include OCLC # prefix

None
isbn str

ISBN without any dashes, example: '978149191646x'

None
issn str

ISSN (hyphenated, example: '0099-1234')

None
holdingsAllEditions bool

get holdings for all editions; options: True or False

None
heldInCountry str

restricts to holdings held by institutions in requested country

None
heldByGroup str

limits to holdings held by indicated by symbol group

None
heldBy str

limits to holdings of single institution, use institution OCLC symbol

None
lat float

limit to latitude, example: 37.502508

None
lon float

limit to longitute, example: -122.22702

None
distance int

distance from latitude and longitude

None
unit str

unit of distance param; options: 'M' (miles) or 'K' (kilometers)

None
offset int

start position of bibliographic records to return; default 1

None
limit int

maximum nuber of records to return; maximum 50, default 10

None

Returns: requests.Response object

Source code in bookops_worldcat\metadata_api.py
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
def search_general_holdings(
    self,
    oclcNumber: Union[int, str] = None,
    isbn: str = None,
    issn: str = None,
    holdingsAllEditions: bool = None,
    heldInCountry: str = None,
    heldByGroup: str = None,
    heldBy: str = None,
    lat: float = None,
    lon: float = None,
    distance: int = None,
    unit: str = None,
    offset: int = None,
    limit: int = None,
    hooks: Dict = None,
):
    """
    Given a known item gets summary of holdings.

    Args:
        oclcNumber:             OCLC bibliographic record number; can be
                                an integer, or string that can include
                                OCLC # prefix
        isbn:                   ISBN without any dashes,
                                example: '978149191646x'
        issn:                   ISSN (hyphenated, example: '0099-1234')
        holdingsAllEditions:    get holdings for all editions;
                                options: True or False
        heldInCountry:          restricts to holdings held by institutions
                                in requested country
        heldByGroup:            limits to holdings held by indicated by
                                symbol group
        heldBy:                 limits to holdings of single institution,
                                use institution OCLC symbol
        lat:                    limit to latitude, example: 37.502508
        lon:                    limit to longitute, example: -122.22702
        distance:               distance from latitude and longitude
        unit:                   unit of distance param; options:
                                'M' (miles) or 'K' (kilometers)
        offset:                 start position of bibliographic records to
                                return; default 1
        limit:                  maximum nuber of records to return;
                                maximum 50, default 10
    Returns:
        `requests.Response` object
    """
    if not any([oclcNumber, isbn, issn]):
        raise WorldcatSessionError(
            "Missing required argument. "
            "One of the following args are required: oclcNumber, issn, isbn"
        )
    if oclcNumber is not None:
        try:
            oclcNumber = verify_oclc_number(oclcNumber)
        except InvalidOclcNumber:
            raise WorldcatSessionError("Invalid OCLC # was passed as an argument")

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    url = self._url_member_general_holdings()
    header = {"Accept": "application/json"}
    payload = {
        "oclcNumber": oclcNumber,
        "isbn": isbn,
        "issn": issn,
        "holdingsAllEditions": holdingsAllEditions,
        "heldInCountry": heldInCountry,
        "heldByGroup": heldByGroup,
        "heldBy": heldBy,
        "lat": lat,
        "lon": lon,
        "distance": distance,
        "unit": unit,
        "offset": offset,
        "limit": limit,
    }

    # send request
    try:
        response = self.get(url, headers=header, params=payload, hooks=hooks)
        if response.status_code == requests.codes.ok:
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Connection error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")

search_shared_print_holdings

search_shared_print_holdings(
    oclcNumber: Union[int, str] = None,
    isbn: str = None,
    issn: str = None,
    heldByGroup: str = None,
    heldInState: str = None,
    offset: int = None,
    limit: int = None,
    hooks: Dict = None,
)

Finds member shared print holdings for specified item.

Parameters:

Name Type Description Default
oclcNumber Union[int, str]

OCLC bibliographic record number; can be an integer, or string that can include OCLC # prefix

None
isbn str

ISBN without any dashes, example: '978149191646x'

None
issn str

ISSN (hyphenated, example: '0099-1234')

None
heldByGroup str

restricts to holdings held by group symbol

None
heldInState str

restricts to holings held by institutions in requested state, example: "NY"

None
offset int

start position of bibliographic records to return; default 1

None
limit int

maximum nuber of records to return; maximum 50, default 10

None

Returns: resquests.Response object

Source code in bookops_worldcat\metadata_api.py
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
def search_shared_print_holdings(
    self,
    oclcNumber: Union[int, str] = None,
    isbn: str = None,
    issn: str = None,
    heldByGroup: str = None,
    heldInState: str = None,
    offset: int = None,
    limit: int = None,
    hooks: Dict = None,
):
    """
    Finds member shared print holdings for specified item.

    Args:
        oclcNumber:             OCLC bibliographic record number; can be
                                an integer, or string that can include
                                OCLC # prefix
        isbn:                   ISBN without any dashes,
                                example: '978149191646x'
        issn:                   ISSN (hyphenated, example: '0099-1234')
        heldByGroup:            restricts to holdings held by group symbol
        heldInState:            restricts to holings held by institutions
                                in requested state, example: "NY"
        offset:                 start position of bibliographic records to
                                return; default 1
        limit:                  maximum nuber of records to return;
                                maximum 50, default 10
        ""
    Returns:
        `resquests.Response` object
    """
    if not any([oclcNumber, isbn, issn]):
        raise WorldcatSessionError(
            "Missing required argument. "
            "One of the following args are required: oclcNumber, issn, isbn"
        )

    if oclcNumber is not None:
        try:
            oclcNumber = verify_oclc_number(oclcNumber)
        except InvalidOclcNumber:
            raise WorldcatSessionError("Invalid OCLC # was passed as an argument")

    # make sure access token is still valid and if not request a new one
    if self.authorization.is_expired():
        self._get_new_access_token()

    url = self._url_member_shared_print_holdings()
    header = {"Accept": "application/json"}
    payload = {
        "oclcNumber": oclcNumber,
        "isbn": isbn,
        "issn": issn,
        "heldByGroup": heldByGroup,
        "heldInState": heldInState,
        "offset": offset,
        "limit": limit,
    }

    # send request
    try:
        response = self.get(url, headers=header, params=payload, hooks=hooks)
        if response.status_code == requests.codes.ok:
            return response
        else:
            error_msg = _parse_error_response(response)
            raise WorldcatRequestError(error_msg)
    except WorldcatRequestError as exc:
        raise WorldcatSessionError(exc)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
        raise WorldcatSessionError(f"Request error: {sys.exc_info()[0]}")
    except:
        raise WorldcatSessionError(f"Unexpected request error: {sys.exc_info()[0]}")