### Configuration File Format Example Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Provides an example of the `config.json` file structure, specifying the required `apikey` and optional `insttoken` fields. ```json { "apikey": "your-api-key-from-dev.elsevier.com", "insttoken": "your-institutional-token" } ``` -------------------------------- ### ElsAuthor Initialization Examples Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsProfile.md Demonstrates creating an ElsAuthor instance using either an author ID or a full URI. These methods are equivalent for instantiation. ```python # Create using author ID author1 = ElsAuthor(author_id="7004367821") # Create using full URI author2 = ElsAuthor(uri="https://api.elsevier.com/content/author/author_id/7004367821") # These are equivalent ``` -------------------------------- ### Example .gitignore Entry Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Illustrates how to add configuration files like `config.json` to a `.gitignore` file to prevent sensitive credentials from being committed to version control. ```text config.json config.local.json .env ``` -------------------------------- ### Example ScienceDirect Search Request Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Provides an example of searching the ScienceDirect index using simple keywords. The query should be URL-encoded. ```http GET /content/search/sciencedirect?query=machine+learning ``` -------------------------------- ### Example Affiliation Search Request Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Illustrates searching for affiliations by name. Ensure the query parameter is URL-encoded. ```http GET /content/search/affiliation?query=affil%28stanford%29 ``` -------------------------------- ### Example Scopus Search with Cursor Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Demonstrates initiating a paginated search in Scopus using the cursor parameter. Set cursor to '*' for the first request. ```http GET /content/search/scopus?query=test&cursor=* ``` -------------------------------- ### Example Author Search Request Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Shows how to search for authors by last name using the author index. The query parameter should be URL-encoded. ```http GET /content/search/author?query=authlast%28smith%29 ``` -------------------------------- ### Define Environment Variables in .env File Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md This example shows how to define API key and institution token in a `.env` file for use with the `python-dotenv` library. ```bash # .env file ELSEVIER_API_KEY=your-api-key ELSEVIER_INST_TOKEN=your-token ``` -------------------------------- ### Example implementation and usage of read method Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsEntity.md Demonstrates how a subclass like ElsAuthor implements the read method and how to use it with a client instance. Ensure a client is available and the read operation is successful before accessing data. ```python # In ElsAuthor (subclass implementation) def read(self, els_client=None): return ElsEntity.read(self, "author-retrieval-response", els_client) # Usage author = ElsAuthor(author_id="7004367821") if author.read(client): print(f"Author loaded: {author.full_name}") else: print("Failed to read author") ``` -------------------------------- ### Example usage of write method Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsEntity.md Shows how to use the write method after successfully reading author data. The file will be saved in the client's configured local directory with a filename based on the entity's URI. ```python author = ElsAuthor(author_id="7004367821") if author.read(client): author.write() # File saved to: client.local_dir / "{encoded_uri}.json" print(f"Author saved to {client.local_dir}") else: print("No data to write") ``` -------------------------------- ### Core Data Structure Example Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/types.md Illustrates the common top-level 'coredata' key found in most elsapy API responses, containing essential metadata. ```python coredata = { "dc:identifier": str, # Full identifier (scheme:id) "dc:title": str, # Title "dc:description": str, # Abstract or description (optional) "dc:creator": str | list, # Author(s) (optional) "prism:publicationName": str, # Publication/venue name "prism:coverDate": str, # Publication date (YYYY-MM-DD format) "prism:doi": str, # DOI (optional) # ... many other optional fields } ``` -------------------------------- ### Affiliation Structure Example Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/types.md Outlines the structure of the affiliation response object obtained from ElsAffil.read(), including name and address details. ```python affiliation_retrieval_response = { "coredata": {...}, # See Core Data structure "affiliation-name": str, # Institution name "address": { "address-part": str, "city": str, "postal-code": str, "country": str, }, # ... many other optional fields } ``` -------------------------------- ### Get Author Data Keys Source: https://github.com/elsevierdev/elsapy/wiki/Understanding-the-data List all available keys within the author's data dictionary. ```python myAuth.data.keys() ``` -------------------------------- ### Example Scopus Search Request Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Demonstrates a search query for Scopus, filtering by affiliation and publication year. Use URL encoding for the query parameter. ```http GET /content/search/scopus?query=AFFIL%28dartmouth%29+AND+PUBYEAR+%3E+2015 ``` -------------------------------- ### Configure ElsClient for Number of Results Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Examples of initializing ElsClient with different values for `num_res` to control the number of results fetched per API request. The `num_res` attribute can also be modified after initialization. ```python # Reduce to 10 results per request (slower, more requests) client = ElsClient(api_key="key", num_res=10) # Increase to 100 results per request (faster, fewer requests) client = ElsClient(api_key="key", num_res=100) # Change after initialization client.num_res = 50 ``` -------------------------------- ### Initialize ElsSearch for Different Indexes Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Instantiate `ElsSearch` with a query string and the desired index name. Examples show document search in 'scopus', author search in 'author', affiliation search in 'affiliation', and full-text search in 'sciencedirect'. ```python from elsapy.elssearch import ElsSearch # Document search doc_search = ElsSearch("PUBYEAR > 2015 AND TITLE(machine learning)", "scopus") # Author search author_search = ElsSearch("authlast(smith)", "author") # Affiliation search affil_search = ElsSearch("affil(stanford)", "affiliation") # Full-text search sd_search = ElsSearch("climate change", "sciencedirect") ``` -------------------------------- ### Automatic Rate Limiting Example Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Demonstrates Elsapy's automatic throttling. The first request executes immediately, while the second is delayed to enforce a minimum 1-second interval between calls. ```python import time from elsapy.elsclient import ElsClient client = ElsClient(api_key="key") # First request executes immediately start = time.time() client.exec_request("https://api.elsevier.com/content/author/author_id/123") # Second request will be delayed to enforce 1-second minimum # This call will sleep for ~0.95 seconds if first request took 0.05s client.exec_request("https://api.elsevier.com/content/author/author_id/456") print(f"Total time for 2 requests: {time.time() - start:.2f}s") # ~1.0s ``` -------------------------------- ### Handling 403 Forbidden Error (Permission Denied) Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/errors.md This example shows how to handle a 403 Forbidden error, which can occur due to an invalid institutional token or insufficient permissions for the requested resource. Verify your institutional token and required permissions. ```python client = ElsClient(api_key="valid-key", inst_token="invalid-token") try: author = ElsAuthor(author_id="7004367821") author.read_docs(client) # May require elevated permissions except requests.HTTPError as e: print(f"Permission denied: {e}") ``` -------------------------------- ### Manual Throttling for Batch Operations Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md This example shows how to implement manual throttling for batch operations by adding an explicit delay using `time.sleep(2)` in addition to the library's automatic 1-second throttling. ```python import time from elsapy.elsclient import ElsClient from elsapy.elsprofile import ElsAuthor client = ElsClient(api_key="key") author_ids = ["7004367821", "7005234561", "7003465211"] for author_id in author_ids: author = ElsAuthor(author_id=author_id) author.read(client) # Add 2-second delay beyond automatic 1-second throttling time.sleep(2) ``` -------------------------------- ### Document Structure (Scopus Abstract) Example Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/types.md Details the structure of the response object for Scopus abstracts obtained from AbsDoc.read(), including core metadata and item details. ```python abstracts_retrieval_response = { "coredata": { "dc:identifier": str, # SCOPUS_ID:xxxxx "dc:title": str, # Article title "dc:description": str, # Abstract text "dc:creator": str | list, # Authors "prism:publicationName": str, # Journal name "prism:coverDate": str, # Publication date # ... many other fields }, "item": { "bibrecord": { "head": { "author": [ { "author-id": str, "preferred-name": { "given-name": str, "surname": str, }, "affiliation": { "affiliation-id": str, "affiliation-name": str, } } ], # ... many other fields } } }, # ... many optional fields } ``` -------------------------------- ### Get and Set Local Data Directory Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Retrieve the path to the directory used for storing downloaded data, or set a new path. The path is returned as a pathlib.Path object. ```python print(f"Data directory: {client.local_dir}") client.local_dir = "/new/data/path" ``` -------------------------------- ### Example Log Output Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/utilities.md This snippet shows the typical format of log messages generated by Elsapy, including timestamp, module, log level, and the message content. These logs are stored in the logs/ directory. ```log 2024-06-19 10:15:32,123 - elsapy.elsclient - INFO - Sending GET request to https://api.elsevier.com/content/author/author_id/7004367821 2024-06-19 10:15:33,456 - elsapy.elsentity - INFO - Data loaded for https://api.elsevier.com/content/author/author_id/7004367821 2024-06-19 10:15:33,789 - elsapy.elsentity - INFO - Wrote https://api.elsevier.com/content/author/author_id/7004367821 to file ``` -------------------------------- ### Get Configured Logger Instance Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/utilities.md Use this function to obtain a logger instance for your module. It configures both file and console handlers with specific logging levels and formats. The log file is created daily in the 'logs/' directory. ```python from elsapy import log_util # Get logger for your module logger = log_util.get_logger(__name__) # Log messages at different levels logger.info("Information message") logger.warning("Warning message") logger.error("Error message") logger.debug("Debug message") ``` -------------------------------- ### Get Number of Stored Results Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsSearch.md Demonstrates how to get the count of results currently stored within the ElsSearch object. This count can be less than the total available results if not all were retrieved. ```python search = ElsSearch("test query", "scopus") search.execute(client, get_all=True) if search.num_res >= 5000: print(f"Retrieved maximum results: {search.num_res}") else: print(f"All results retrieved: {search.num_res}") ``` -------------------------------- ### Initialize ElsClient from environment variables Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Initialize the ElsClient using API key and institutional token from environment variables. Use 'ELSEVIER_API_KEY' and optionally 'ELSEVIER_INST_TOKEN'. ```python import os from elsapy.elsclient import ElsClient client = ElsClient( api_key=os.environ['ELSEVIER_API_KEY'], inst_token=os.environ.get('ELSEVIER_INST_TOKEN') ) ``` -------------------------------- ### Set and Get API Key Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Access or modify the API key used by the ElsClient instance. ```python client.api_key = "new-api-key" print(client.api_key) ``` -------------------------------- ### Initialize ElsClient with API Key Source: https://github.com/elsevierdev/elsapy/wiki/Establishing-an-API-interface-for-your-program Instantiate the ElsClient using your unique API key obtained from dev.elsevier.com. This is the primary method for establishing an API interface. ```python myCl = ElsClient('[my_api_key]') ``` -------------------------------- ### Initialize ElsClient with Config File Source: https://github.com/elsevierdev/elsapy/wiki/Establishing-an-API-interface-for-your-program Load API and institution tokens from a 'config.json' file to initialize the ElsClient. This method is useful for managing credentials securely. ```python ## Load configuration conFile = open("config.json") config = json.load(conFile) conFile.close() ## Initialize client myCl = ElsClient(config['apikey']) myCl.inst_token = config['insttoken'] ``` -------------------------------- ### Get Affiliation Name Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsProfile.md Retrieve the name of the affiliation after successfully reading its data. Requires an initialized ElsClient. ```python affil = ElsAffil(affil_id="60101411") if affil.read(client): print(f"Affiliation: {affil.name}") # Output: "Dartmouth College" ``` -------------------------------- ### Get Base URL Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Retrieve the base URL for the Elsevier API. This is the root endpoint for all API calls. ```python base = client.getBaseURL() print(base) # Output: https://api.elsevier.com/ ``` -------------------------------- ### Initialize ElsClient Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/README.md Initialize the `ElsClient` by loading credentials from `config.json`. The institutional token is optional. ```python import json from elsapy.elsclient import ElsClient with open("config.json") as f: config = json.load(f) client = ElsClient( api_key=config['apikey'], inst_token=config.get('insttoken') ) ``` -------------------------------- ### Set and Get Number of Results Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Configure or retrieve the maximum number of results returned per API request. ```python client.num_res = 50 print(f"Results per request: {client.num_res}") ``` -------------------------------- ### Initialize ElsClient with API Key Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Demonstrates the typical pattern for initializing the ElsClient using an API key loaded from a configuration file. This client instance is required for other elsapy objects to make API calls. ```python import json from elsapy.elsclient import ElsClient # Load credentials from config file with open("config.json") as f: config = json.load(f) # Create client client = ElsClient( api_key=config['apikey'], inst_token=config.get('insttoken') ) # Client is now ready to be passed to other elsapy objects ``` -------------------------------- ### Set and Get Institutional Token Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Access or modify the institutional token for the ElsClient instance. Check if a token is configured. ```python client.inst_token = "your-inst-token" if client.inst_token: print("Institutional token configured") ``` -------------------------------- ### Scopus Abstract Document Response Structure Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Example JSON payload for a successful request to the Scopus abstract document endpoint. ```json { "abstracts-retrieval-response": [ { "coredata": { "dc:identifier": "SCOPUS_ID:84872135457", "dc:title": "Document Title", "dc:description": "Abstract text...", "dc:creator": "Author Name", "prism:publicationName": "Journal Name", "prism:coverDate": "2020-01-15" }, "item": { "bibrecord": { "head": { "author": [ { "author-id": "7004367821", "preferred-name": { "given-name": "John", "surname": "Doe" } } ] } } } } ] } ``` -------------------------------- ### Initialize Elsapy Client Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/INDEX.md Create an instance of the ElsClient to interact with the Elsevier API. Requires an API key and optionally an institution token. ```python client = ElsClient(api_key="your-key", inst_token="optional-token") ``` -------------------------------- ### Python Code to Load Configuration and Initialize ElsClient Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/types.md Load credentials from a 'config.json' file and initialize the ElsClient. Uses `json.load` for parsing and `config.get` for optional institutional token. ```python import json with open("config.json") as f: config = json.load(f) client = ElsClient( api_key=config['apikey'], inst_token=config.get('insttoken') ) ``` -------------------------------- ### Get Request Status Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Retrieve the status of the most recent HTTP request made by the client. The status includes the code and message. ```python client.exec_request("https://api.elsevier.com/content/author/author_id/12345") status = client.req_status print(f"Status: {status['status_code']} - {status['status_msg']}") ``` -------------------------------- ### Fetch and Display Author Information Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsProfile.md Demonstrates how to initialize ElsClient, create an ElsAuthor object, read author details, and optionally load metrics and documents. Requires an API key. ```python from elsapy.elsclient import ElsClient from elsapy.elsprofile import ElsAuthor, ElsAffil client = ElsClient(api_key="your-key", inst_token="optional-token") # Author example author = ElsAuthor(author_id="7004367821") if author.read(client): print(f"Author: {author.full_name}") print(f"ID: {author.int_id}") # Load metrics (requires elevated permissions) if author.read_metrics(client): print(f"H-index: {author.data['h-index']}") # Load documents (requires elevated permissions) if author.read_docs(client): print(f"Documents: {len(author.doc_list)}") author.write_docs() ``` -------------------------------- ### Configure API Credentials Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/README.md Create a `config.json` file to store your API key and institutional token. Ensure this file is added to your `.gitignore` to prevent accidental commits. ```json { "apikey": "your-api-key-here", "insttoken": "your-institutional-token" } ``` ```gitignore config.json ``` -------------------------------- ### FullDoc Usage Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsDocument.md Demonstrates how to initialize and read a FullDoc object using either a PII or DOI, and how to access its data. ```APIDOC ## FullDoc Usage ### Description This section shows how to use the `FullDoc` class to retrieve full-text articles. You can initialize a `FullDoc` object with either a ScienceDirect PII or a DOI. The `read()` method fetches the article data using an `ElsClient`. ### Method `FullDoc.read(client)` ### Parameters #### Initialization Parameters - **sd_pii** (string) - Optional - The ScienceDirect Persistent Identifier (PII) of the article. - **doi** (string) - Optional - The Digital Object Identifier (DOI) of the article. #### Read Method Parameters - **client** (`ElsClient`) - Required - An authenticated `ElsClient` instance. ### Request Example (Initialization and Read) ```python from elsapy.elsclient import ElsClient from elsapy.elsdoc import FullDoc client = ElsClient(api_key="your-key") # Example 1: Using PII pii_doc = FullDoc(sd_pii='S1674927814000082') if pii_doc.read(client): print(f"Title: {pii_doc.title}") print(f"ID: {pii_doc.int_id}") pii_doc.write() # Example 2: Using DOI doi_doc = FullDoc(doi='10.1016/S1525-1578(10)60571-5') if doi_doc.read(client): print(f"Title: {doi_doc.title}") # Access full-text data fulltext = doi_doc.data.get('full-text') coredata = doi_doc.data['coredata'] # Inspect available keys print(f"Available data keys: {doi_doc.data.keys()}") ``` ### Response Upon successful reading, the `FullDoc` object will be populated with data. Key attributes include: - **title** (string) - The title of the article. - **int_id** (string) - The internal ID of the article. - **data** (dict) - A dictionary containing various article data, including 'full-text' and 'coredata'. ``` -------------------------------- ### Author Profile Structure Example Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/types.md Details the structure of the 'author-profile' object returned by ElsAuthor.read(), including name variants and current affiliation. ```python author_retrieval_response = { "coredata": {...}, # See Core Data structure "author-profile": { "preferred-name": { "given-name": str, "surname": str, "initials": str, }, "name-variants": [ # Alternative name spellings { "given-name": str, "surname": str, "initials": str, } ], "affiliation-current": { "affiliation-id": str, "affiliation-name": str, # ... other affiliation details }, # ... many other optional profile fields }, "h-index": int, # H-index metric (after read_metrics) # ... many optional fields } ``` -------------------------------- ### Initialize FullDoc with Different Identifiers Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsDocument.md Demonstrates initializing a FullDoc object using a ScienceDirect PII, a DOI, or a full URI. Ensure only one identifier type is provided. ```python from elsapy.elsdoc import FullDoc # Using PII doc1 = FullDoc(sd_pii='S1674927814000082') # Using DOI doc2 = FullDoc(doi='10.1016/S1525-1578(10)60571-5') # Using full URI doc3 = FullDoc(uri='https://api.elsevier.com/content/article/pii/S1674927814000082') ``` -------------------------------- ### Handling Multiple Documents Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsDocument.md Provides examples for processing multiple documents, either Scopus abstracts or ScienceDirect full-text articles, in batches. ```APIDOC ## Handling Multiple Documents ### Description This section demonstrates how to efficiently process multiple documents by iterating through lists of identifiers (Scopus IDs or PIIs) and retrieving their data using `AbsDoc` or `FullDoc` respectively. ### Method `AbsDoc.read(client)` and `FullDoc.read(client)` within loops. ### Parameters - **scopus_ids** (list of integers) - A list of Scopus IDs to process. - **piis** (list of strings) - A list of ScienceDirect PIIs to process. - **client** (`ElsClient`) - Required - An authenticated `ElsClient` instance. ### Request Example (Batch Processing) ```python from elsapy.elsclient import ElsClient from elsapy.elsdoc import FullDoc, AbsDoc client = ElsClient(api_key="your-key") # Process multiple Scopus documents scopus_ids = [84872135457, 78651360840, 70350646106] for doc_id in scopus_ids: doc = AbsDoc(scp_id=doc_id) if doc.read(client): print(f"✓ {doc.title}") else: print(f"✗ Failed to read document {doc_id}") # Process multiple ScienceDirect documents piis = ['S1674927814000082', 'S0140673620305377'] for pii in piis: doc = FullDoc(sd_pii=pii) if doc.read(client): print(f"✓ {doc.title}") else: print(f"✗ Failed to read document {pii}") ``` ### Response This method provides feedback on the success or failure of reading each document in the batch, printing the title for successful reads or an error message for failures. ``` -------------------------------- ### Initialize ElsAffil with Affiliation ID or URI Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsProfile.md Instantiate an ElsAffil object using either a Scopus affiliation ID or a full Scopus affiliation URI. Ensure only one of these parameters is provided. ```python affil1 = ElsAffil(affil_id="60101411") # Create using full URI affil2 = ElsAffil(uri="https://api.elsevier.com/content/affiliation/affiliation_id/60101411") ``` -------------------------------- ### Modifying Logging Level in elsapy Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/utilities.md Illustrates how to modify the logging level within `elsapy/log_util.py` to change the default behavior, for example, from DEBUG to WARNING. ```python # In elsapy/log_util.py def get_logger(name): logger = logging.getLogger(name) logger.setLevel(logging.WARNING) # Change from DEBUG # ... rest of configuration ... ``` -------------------------------- ### Initialize Multiple Elsapy Clients Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Create separate ElsClient instances for different API keys and local directories to manage distinct use cases. Each client has independent throttling state. ```python from elsapy.elsclient import ElsClient # Create separate clients for different use cases client_researcher1 = ElsClient(api_key="key1", local_dir="/data/researcher1") client_researcher2 = ElsClient(api_key="key2", local_dir="/data/researcher2") # Use appropriate client for each operation author1 = ElsAuthor(author_id="123") author1.read(client_researcher1) author2 = ElsAuthor(author_id="456") author2.read(client_researcher2) ``` -------------------------------- ### Get Request URI Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsSearch.md Shows how to retrieve the base URI that the ElsSearch object uses to make its API requests, excluding pagination parameters. ```python search = ElsSearch("test", "scopus") print(f"Request URI: {search.uri}") # Output: https://api.elsevier.com/content/search/scopus?query=test ``` -------------------------------- ### Fetch and Access ElsAuthor Data Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsEntity.md Demonstrates the typical workflow for creating an ElsAuthor instance, setting the client, reading data from the API, and accessing specific fields. Ensure a valid API key and author ID are used. ```python from elsapy.elsclient import ElsClient from elsapy.elsprofile import ElsAuthor # Create client client = ElsClient(api_key="your-key") # Create entity instance with URI or ID author = ElsAuthor(author_id="7004367821") # Set client (either here or pass to read()) author.client = client # Read data from API if author.read(): # Access data print(f"Full name: {author.full_name}") print(f"ID: {author.id}") print(f"Numeric ID: {author.numeric_id}") # Access raw data dictionary profile_data = author.data['author-profile'] # Write to disk author.write() else: print("Failed to fetch author data") ``` -------------------------------- ### ElsClient Constructor Parameters Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Defines the parameters for initializing the ElsClient, including API key, institutional token, number of results per request, and local data directory. ```python ElsClient( api_key: str, inst_token: str | None = None, num_res: int = 25, local_dir: str | pathlib.Path | None = None ) ``` -------------------------------- ### Get AbsDoc Title Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsDocument.md Retrieve the title of the document. This property accesses the 'dc:title' field within the 'coredata' of the document's data. ```python doc = AbsDoc(scp_id=84872135457) if doc.read(client): print(f"Title: {doc.title}") ``` -------------------------------- ### Elsapy Configuration File Source: https://github.com/elsevierdev/elsapy/blob/master/CONFIG.md Create a 'config.json' file in your project directory and insert your API key and institution token. Ensure your API key is obtained from the Elsevier developer portal. ```json { "apikey": "ENTER_APIKEY_HERE", "insttoken": "ENTER_INSTTOKEN_HERE_IF_YOU_HAVE_ONE_ELSE_DELETE" } ``` -------------------------------- ### Fetch and Display Affiliation Information Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsProfile.md Shows how to create an ElsAffil object, read affiliation details, and load associated documents. Requires an API key. ```python # Affiliation example affil = ElsAffil(affil_id="60101411") if affil.read(client): print(f"Affiliation: {affil.name}") if affil.read_docs(client): print(f"Affiliation has {len(affil.doc_list)} documents") ``` -------------------------------- ### Retrieve Affiliation Profile Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Use this endpoint to get the basic profile and metadata for a given Scopus affiliation ID. The `ElsAffil.read()` method utilizes this endpoint. ```http GET /content/affiliation/affiliation_id/60101411 ``` -------------------------------- ### Access Entity Data Safely After Reading Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/errors.md Ensure `read()` is called on an entity before accessing its data attributes to avoid `TypeError`. This example demonstrates the correct sequence. ```python author = ElsAuthor(author_id="7004367821") name = author.full_name # TypeError: 'NoneType' object is not subscriptable ``` ```python author = ElsAuthor(author_id="7004367821") if author.read(client): name = author.full_name # Now works ``` -------------------------------- ### ElsClient Configuration File Format Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Shows the expected JSON format for the configuration file used to load API keys and institution tokens for ElsClient initialization. ```json { "apikey": "your-api-key", "insttoken": "your-inst-token" } ``` -------------------------------- ### GET /content/author/author_id/{author_id} Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Retrieve author profile and metadata using their Scopus author ID. This endpoint provides core author information and their preferred name. ```APIDOC ## GET /content/author/author_id/{author_id} ### Description Retrieve author profile and metadata. ### Method GET ### Endpoint /content/author/author_id/{author_id} ### Parameters #### Path Parameters - **author_id** (string or int) - Required - Scopus author ID ### Response #### Success Response (200) - **author-retrieval-response** (object) - Contains author data including coredata and author-profile. ### Response Example ```json { "author-retrieval-response": [ { "coredata": { "dc:identifier": "SCOPUS_ID:7004367821", "dc:title": "Author Name" }, "author-profile": { "preferred-name": { "given-name": "John", "surname": "Doe" }, "name-variants": [], "affiliation-current": { "affiliation-id": "60101411", "affiliation-name": "Dartmouth College" } } } ] } ``` ``` -------------------------------- ### Configure ElsClient Local Data Directory Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Demonstrates various ways to specify the local directory for storing downloaded data using ElsClient, including default, absolute, relative, and pathlib.Path options. ```python # Using default ./data directory client = ElsClient(api_key="key") print(client.local_dir) # PosixPath('data') or WindowsPath('data') # Using absolute path client = ElsClient(api_key="key", local_dir="/home/user/elsapy_data") # Using relative path client = ElsClient(api_key="key", local_dir="./downloads/elsevier") # Using pathlib.Path import pathlib data_dir = pathlib.Path.home() / ".elsapy" / "data" client = ElsClient(api_key="key", local_dir=data_dir) ``` -------------------------------- ### Retrieve All Documents by Author Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/INDEX.md After fetching an author's profile, use `read_docs()` to get a list of all their associated documents. The number of documents can be accessed via `author.doc_list`. ```python if author.read_docs(client): print(f"Documents: {len(author.doc_list)}") ``` -------------------------------- ### Execute API Request Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsClient.md Perform a GET request to a specified URL, including authentication and rate limiting. Handles JSON parsing and raises exceptions for errors. ```python import json client = ElsClient(api_key="your-api-key") # Fetch author data author_url = "https://api.elsevier.com/content/author/author_id/7004367821" try: response = client.exec_request(author_url) author_data = response['author-retrieval-response'][0] print(f"Author: {author_data['author-profile']['preferred-name']['given-name']}") except requests.HTTPError as e: print(f"Request failed: {e}") ``` -------------------------------- ### GET /content/author/author_id/{author_id}?field={fields} Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Retrieve specific metrics for an author, allowing selection of desired fields. This endpoint is useful for obtaining author performance indicators. ```APIDOC ## GET /content/author/author_id/{author_id}?field={fields} ### Description Retrieve specific metrics for an author. ### Method GET ### Endpoint /content/author/author_id/{author_id} ### Parameters #### Path Parameters - **author_id** (string or int) - Required - Scopus author ID #### Query Parameters - **field** (string) - Required - Comma-separated list of fields to retrieve ### Request Example ``` GET /content/author/author_id/7004367821?field=document-count,cited-by-count,citation-count,h-index,dc:identifier ``` ### Response #### Success Response (200) - **author-retrieval-response** (object) - Contains author data including requested metrics. ### Supported Metrics - **document-count** (int) - Number of documents - **cited-by-count** (int) - Number of citations - **citation-count** (int) - Citation count (may be same as cited-by-count) - **h-index** (int) - H-index value - **dc:identifier** (string) - Author identifier ``` -------------------------------- ### Search for Documents Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/INDEX.md Initialize an ElsSearch object with a query and index, then execute the search. Use `get_all=True` to retrieve all matching results. The total number of results is stored in `search.num_res`. ```python from elsapy.elssearch import ElsSearch search = ElsSearch("PUBYEAR > 2015", "scopus") search.execute(client, get_all=True) print(f"Found {search.num_res} documents") ``` -------------------------------- ### GET /content/author/author_id/{author_id}?view=documents Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/endpoints.md Retrieve a list of documents published by a specific author, supporting pagination. This endpoint is useful for fetching an author's publication history. ```APIDOC ## GET /content/author/author_id/{author_id}?view=documents ### Description Retrieve list of documents published by an author (with pagination support). ### Method GET ### Endpoint /content/author/author_id/{author_id} ### Parameters #### Path Parameters - **author_id** (string or int) - Required - Scopus author ID #### Query Parameters - **view** (string) - Required - Fixed value: `documents` - **startref** (int) - Optional - Offset for next batch of results ### Request Example ``` GET /content/author/author_id/7004367821?view=documents GET /content/author/author_id/7004367821?view=documents&startref=26 ``` ### Response #### Success Response (200) - **author-retrieval-response** (object) - Contains author data including coredata and documents. ### Response Example ```json { "author-retrieval-response": [ { "coredata": {...}, "documents": { "@total": "145", "abstract-document": [ { "dc:identifier": "SCOPUS_ID:84872135457", "dc:title": "Document Title", "prism:coverDate": "2020-01-15", "prism:publicationName": "Journal Name" } ] } } ] } ``` ``` -------------------------------- ### get_logger(name) Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/utilities.md Get a configured logger instance for a module. This function creates and configures a logger with both file and console handlers, providing centralized logging for elsapy modules. ```APIDOC ## Function: get_logger(name) ### Description Get a configured logger instance for a module. Creates and configures a logger with both file and console handlers. ### Signature ```python def get_logger(name: str) -> logging.Logger ``` ### Parameters #### Path Parameters - **name** (str) - Required - Logger name (typically `__name__` of the calling module) ### Returns - **logging.Logger** - Configured logger instance ### Logger Configuration | Handler | Level | Output | Format | |---|---|---|---| | File | DEBUG | `logs/elsapy-YYYYMMDD.log` | Full timestamp, module, level, message | | Console | ERROR | stdout/stderr | Full timestamp, module, level, message | ### Features - File handler logs all DEBUG level messages - Console handler only logs ERROR level messages - Logs are written to `logs/` subdirectory (created if missing) - New log file created each day (filename includes date) - Format includes timestamp, module name, log level, and message ### Example ```python from elsapy import log_util # Get logger for your module logger = log_util.get_logger(__name__) # Log messages at different levels logger.info("Information message") logger.warning("Warning message") logger.error("Error message") logger.debug("Debug message") ``` ``` -------------------------------- ### Handle Missing Configuration File Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Gracefully handle cases where the 'config.json' file is not found by printing an error message and exiting the application. ```python import json try: with open("config.json") as f: config = json.load(f) except FileNotFoundError: print("Error: config.json not found") exit(1) ``` -------------------------------- ### Initialize AbsDoc with Scopus ID or URI Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsDocument.md Initialize a Scopus document using either a Scopus ID (integer or string) or a full abstract URI. Exactly one identifier must be provided. ```python from elsapy.elsdoc import AbsDoc # Using Scopus ID as integer doc1 = AbsDoc(scp_id=84872135457) # Using Scopus ID as string doc2 = AbsDoc(scp_id='84872135457') # Using full URI doc3 = AbsDoc(uri='https://api.elsevier.com/content/abstract/scopus_id/84872135457') ``` -------------------------------- ### Load API Credentials from .env File using python-dotenv Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md This Python snippet uses the `dotenv` library to load API credentials from a `.env` file and then initializes the ElsClient. It ensures that environment variables are loaded before accessing them. ```python from dotenv import load_dotenv import os from elsapy.elsclient import ElsClient load_dotenv() client = ElsClient( api_key=os.environ['ELSEVIER_API_KEY'], inst_token=os.environ.get('ELSEVIER_INST_TOKEN') ) ``` -------------------------------- ### Accessing and Updating Entity URI Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsEntity.md Demonstrates how to get and set the Uniform Resource Identifier (URI) for an entity instance. The URI uniquely identifies the entity within the Elsevier API. ```python author = ElsAuthor(uri="https://api.elsevier.com/content/author/author_id/7004367821") print(author.uri) # Update URI author.uri = "https://api.elsevier.com/content/author/author_id/9999999999" ``` -------------------------------- ### Retrieve Search Results Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/api-reference/ElsSearch.md Illustrates how to execute a search and then access the retrieved results as a list of dictionaries. It also shows how to iterate through the first few results. ```python search = ElsSearch("test query", "scopus") search.execute(client) results = search.results print(f"Retrieved {len(results)} results") for result in results[:5]: print(f" - {result.get('dc:title', 'Untitled')}") ``` -------------------------------- ### Handling Validation Errors during Object Construction Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/types.md Catch `ValueError` exceptions for invalid arguments passed to constructors like `ElsAuthor` or `ElsAffil`. This example shows handling missing required identifiers. ```python try: author = ElsAuthor(author_id="123") author.read(client) # No client set, will raise ValueError except ValueError as e: print(f"Configuration error: {e}") ``` -------------------------------- ### Initialize ElsClient from Python dictionary Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Initialize the ElsClient by providing credentials directly in a Python dictionary. This is useful for hardcoding or dynamic dictionary creation. ```python from elsapy.elsclient import ElsClient credentials = { 'apikey': 'your-api-key', 'insttoken': 'optional-token' } client = ElsClient( api_key=credentials['apikey'], inst_token=credentials.get('insttoken') ) ``` -------------------------------- ### Handle Network Errors with RequestException Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/errors.md Use a try-except block to catch `requests.RequestException` which can occur due to network issues, timeouts, or connection refusals. This example shows a basic error message. ```python client = ElsClient(api_key="your-key") try: author = ElsAuthor(author_id="7004367821") author.read(client) except requests.RequestException as e: print(f"Network error: {e}") ``` -------------------------------- ### Store API Key in config.json Source: https://github.com/elsevierdev/elsapy/blob/master/_autodocs/configuration.md Demonstrates the recommended JSON format for storing API keys in a configuration file. This file should be added to .gitignore for security. ```json { "apikey": "your-api-key-here" } ```