# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.scicrunch.io/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Introduction

Overview of the FAIR Data Informatics Laboratory's APIs hosted at api.scicrunch.io

The APIs and associated services are provided by the FAIR Data Informatics Laboratory at the University of California, San Diego.  Access to APIs is provided via api.scicrunch.io through an API Service Gateway. There are a number of APIs provided for the research community that are discussed in sections of this handbook:

* Metadata Search via Elasticsearch
  * Resource Information Network (Research Resource Identifiers - RRIDs)
  * SPARC Datasets
* InterLex Terminology
  * Search via Elasticsearch
* Knowledge Graph Services (Coming Soon to the API Gateway)


# Getting Started with the APIs

Instructions for getting started with the APIs

The APIs and associated services are provided by the FAIR Data Informatics Laboratory at the University of California, San Diego.  Access to APIs is provided via scicrunch.org. In order to gain access to the APIs please follow the steps below to get your API key.

{% hint style="warning" %}
**Note:** Once you have generated an API key it may take **15-20 minutes** to propagate to associated services. If you have an issue with your API key please contact <info@scicrunch.org>
{% endhint %}

#### Create an account at [scicrunch.org](https://scicrunch.org)

Go to <https://scicrunch.org> and select 'Register'

![The FAIR Data Informatics Laboratories Portal](https://content.gitbook.com/content/IFPUklTpgWYMOYnZkrEP/blobs/M3W7ahWWMYPcVbVHohjd/image.png)

#### Create your API Key

After you have created your account and verified your email you can then create your API.  First login to the [scicrunch.org portal](https://scicrunch.org). After you are logged in you can select ***API Keys*** under ***MY ACCOUNT***.

![](https://content.gitbook.com/content/IFPUklTpgWYMOYnZkrEP/blobs/xZ1WrFct5QLiirJbzZc6/image.png)

Once you select ***API Keys*** you will be asked to re-verify your password.

![](https://content.gitbook.com/content/IFPUklTpgWYMOYnZkrEP/blobs/m3RgWh3aCquMtWbTawLu/image.png)

Once you have entered your password you will be taken to your API dashboard.

![](https://content.gitbook.com/content/IFPUklTpgWYMOYnZkrEP/blobs/FsZ0bLixg0GgiJgm5EN9/image.png)

From the dashboard you can view your current API keys and can generate an API Key.  The generate a new key select ***Generate an API Key***. A new key will then be added to your dashboard.  To add information to your API key such as the project for which this API key is to be used in and a description - just fill out the information in the available text boxes and select ***Update Text***.

Now that you have your API key you can explore specific SPARC APIs in the following sections.

{% hint style="warning" %}
**Note:** Once you have generated an API key it may take **15-20 minutes** to propagate to associated services. If you have an issue with your API key please contact <info@scicrunch.org>
{% endhint %}


# Using your API key

Overview of API key usage

The preferred method to authenticate with your API key is through the use of an apikey submitted as part of the HTTP header for the request.&#x20;

Examples for authentication are provided through some simple CURL requests using the Resource Information Network Services

{% tabs %}
{% tab title="HTTP Header" %}
{% code overflow="wrap" %}

```sh
curl -i --verbose --location 'https://api.scicrunch.io/elastic/v1/_cat/aliases' --header 'apikey: <<YOUR API KEY>>'
```

{% endcode %}
{% endtab %}

{% tab title="URL Query Paramter" %}
{% code overflow="wrap" %}

```sh
curl -i --verbose --location 'https://api.scicrunch.io/elastic/v1/_cat/aliases?key=<<YOUR API KEY>>'
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}

## Best Practice

Use the apikey HTTP header for authentication
{% endhint %}


# API Rate Limiting

API access is rate limited per user. The 10 requests per second (rps) baseline is adequate for most applications and users. The 10 rps allows for data access, while also minimizing the risk of resource outages due to excessive service calls or requests from any single access node or user cohort. If you require a higher rate limit for your API key, please write to <info@scicrunch.org> including documentation of the reasons for such enhanced access. We may then grant a higher rate limit for your existing API key.&#x20;

{% hint style="info" %}
API access is rate limited to 10 requests per second.  If you require enhanced access please contact <info@scicrunch.org>
{% endhint %}


# API Service Gateway Responses

Overview of API Service Gateway Responses

Responses from API services available via the API Gateway will generally be in JSON format. If a service utilizes a different response format that will be documented with that specific service.

## CORS Support

Services provide support for Cross-Origin Resource Sharing (CORS). CORS is a mechanism that allows restricted resources on a web page to be accessed from another domain outside the domain from which the first resource was served (<https://en.wikipedia.org/wiki/Cross-origin_resource_sharing>)

{% code overflow="wrap" %}

```bash
curl -X OPTIONS --verbose --location 'https://api.scicrunch.io/elastic/v1/_cat/aliases' --header 'apikey: <<YOUR API KEY>>'
```

{% endcode %}

```
*   Trying 52.89.161.7:443...
* Connected to api.scicrunch.io (52.89.161.7) port 443
* ALPN: curl offers h2,http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
*  CAfile: /etc/pki/tls/certs/ca-bundle.crt
*  CApath: none
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-ECDSA-AES128-GCM-SHA256
* ALPN: server accepted http/1.1
* Server certificate:
*  subject: CN=api.scicrunch.io
*  start date: Feb  2 22:02:47 2024 GMT
*  expire date: May  2 22:02:46 2024 GMT
*  subjectAltName: host "api.scicrunch.io" matched cert's "api.scicrunch.io"
*  issuer: C=US; O=Let's Encrypt; CN=R3
*  SSL certificate verify ok.
* using HTTP/1.1
> OPTIONS /elastic/_cat/aliases HTTP/1.1
> Host: api.scicrunch.io
> User-Agent: curl/8.3.0
> Accept: */*
> apikey: <<YOUR API KEY>>
> 
< HTTP/1.1 200 OK
< Server: openresty/1.25.3.1
< Date: Tue, 06 Feb 2024 02:08:25 GMT
< Content-Type: application/json
< Content-Length: 0
< Connection: keep-alive
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD
< Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept
< 
* Connection #0 to host api.scicrunch.io left intact

```


# Resource Information Network (RIN) Services

## Introduction

The RIN metadata APIs are provided via an ElasticSearch endpoint.  The metadata is extracted from Community Authorities that provide information about research resourced identified by a Research Resource Identifier (RRID).  The data from these authorities is processed via the FDI Lab's Foundry - a message-oriented, horizontally scalable ETL system for scientific data integration and enhancement (Ozyurt and Grethe 2018).&#x20;

### Research Resource Identifiers (RRIDs)

RRIDs are meant to improve the standards of research resource reporting in order to support rigor and reproducibility. RRID's original concept was envisioned during NIH meetings in 2010-2011. These meetings, which were hosted by NIH’s National Center for Research Resources, involved the development of an initial white paper on resource identification by principal investigators for dkNET (Drs. Maryann Martone and Jeffrey Grethe) and the current lead for the RRID project (Dr. Anita Bandrowski). This white paper was posted in 2012.  [The Research Resource Initiative](https://www.force11.org/node/4145) was then started by Dr. Maryann Martone, through the[ Neuroscience Information Framework](https://neuinfo.org//) (NIF).  Initially, meetings with publishers from 2011-2013 (hosted by NIF, NIH’s NIDA and [the International Neuroinformatics Coordinating Facility (INCF)](https://www.incf.org/) were held to discuss the problem of research resource identification. From the potential solutions discussed in these meetings, a pilot project was born. This project was started in 2014 and led by Drs. Martone and Bandrowski. It was initiated through FORCE11 with leverage, infrastructure, and support from dkNET. Through this framework from dkNET, the initial RRID portal was created. The pilot included additional partners (i.e. the Oregon Health & Science University Library and[ the Monarch Initiative](https://monarchinitiative.org/)). In 2015, the pilot project concluded. A publication describing how RRIDs were being used by authors in 100 papers from 20 journals was released. The publication described how the use of RRIDs was showing potential for benefiting the accurate reproducibility of research in the scientific community. In respect to this potential, RRIDs are currently being used in over 340 journals (August, 2017). The RRID project is supported by leadership of Dr. Anita Bandrowski and works in collaboration with [SciCrunch](https://scicrunch.org/), [NIF](https://neuinfo.org/), and [dkNET](https://dknet.org/).

RRIDs are persistent and unique identifiers for referencing a research resource and are used for promoting research resource identification and tracking. Catalog numbers change, disappear or can be reused for another resource, but RRIDs always resolve to the same research resource and endure beyond the existence of the research resource itself. It’s an easy and practical method for improving reproducibility, transparency and tracking.

Examples of RRIDs:

* Antibody: [Estrogen receptor beta antibody](https://dknet.org/data/record/nif-0000-07730-1/AB_10618531/resolver), RRID:AB\_10618531
* Cell line: [HK-2 \[Human kidney\]](https://dknet.org/data/record/SCR_013869-1/CVCL_0302/resolver), RRID:CVCL\_0302
* Mouse model: [TSOD.C-Nidd6](https://dknet.org/data/record/nlx_154697-1/IMSR_CARD:280/resolver), RRID:IMSR\_-CARD:280
* Software: [ANOVA](https://dknet.org/data/record/nlx_144509-1/SCR_002427/resolver), RRID:SCR\_002427

### References

Ozyurt, I. B., & Grethe, J. S. (2018). Foundry: a message-oriented, horizontally scalable ETL system for scientific data integration and enhancement. Database : the journal of biological databases and curation, 2018, bay130. <https://doi.org/10.1093/database/bay130>


# Research Resource Identifiers

{% embed url="<https://www.slideshare.net/dkNET/identifying-and-tracking-research-resources-using-rrids-a-practical-approach>" %}

### What are RRIDs?&#x20;

RRIDs are meant to improve the standards of research resource reporting in order to support rigor and reproducibility. RRID's original concept was envisioned during NIH meetings in 2010-2011. These meetings, which were hosted by NIH’s National Center for Research Resources, involved the development of an initial white paper on resource identification by principal investigators for dkNET (Drs. Maryann Martone and Jeffrey Grethe) and the current lead for the RRID project (Dr. Anita Bandrowski). This white paper was posted in 2012.  [The Research Resource Initiative](https://www.force11.org/node/4145) was then started by Dr. Maryann Martone, through the[ Neuroscience Information Framework](https://neuinfo.org//) (NIF).  Initially, meetings with publishers from 2011-2013 (hosted by NIF, NIH’s NIDA and [the International Neuroinformatics Coordinating Facility (INCF)](https://www.incf.org/) were held to discuss the problem of research resource identification. From the potential solutions discussed in these meetings, a pilot project was born. This project was started in 2014 and led by Drs. Martone and Bandrowski. It was initiated through FORCE11 with leverage, infrastructure, and support from dkNET. Through this framework from dkNET, the initial RRID portal was created. The pilot included additional partners (i.e. the Oregon Health & Science University Library and[ the Monarch Initiative](https://monarchinitiative.org/)). In 2015, the pilot project concluded. A publication describing how RRIDs were being used by authors in 100 papers from 20 journals was released. The publication described how the use of RRIDs was showing potential for benefiting the accurate reproducibility of research in the scientific community. In respect to this potential, RRIDs are currently being used in over 340 journals (August, 2017). The RRID project is supported by leadership of Dr. Anita Bandrowski and works in collaboration with [SciCrunch](https://scicrunch.org/), [NIF](https://neuinfo.org/), and [dkNET](https://dknet.org/).

RRIDs are persistent and unique identifiers for referencing a research resource and are used for promoting research resource identification and tracking. Catalog numbers change, disappear or can be reused for another resource, but RRIDs always resolve to the same research resource and endure beyond the existence of the research resource itself. It’s an easy and practical method for improving reproducibility, transparency and tracking.

Examples of RRIDs:

* Antibody: [Estrogen receptor beta antibody](https://dknet.org/data/record/nif-0000-07730-1/AB_10618531/resolver), RRID:AB\_10618531
* Cell line: [HK-2 \[Human kidney\]](https://dknet.org/data/record/SCR_013869-1/CVCL_0302/resolver), RRID:CVCL\_0302
* Mouse model: [TSOD.C-Nidd6](https://dknet.org/data/record/nlx_154697-1/IMSR_CARD:280/resolver), RRID:IMSR\_-CARD:280
* Software: [ANOVA](https://dknet.org/data/record/nlx_144509-1/SCR_002427/resolver), RRID:SCR\_002427

### Why do we need RRIDs?&#x20;

During the publication process, reported resource identifying information is typically lacking. Furthermore, no standard way of referencing a resource in a paper or grant has been implemented. This makes it a serious challenge for human or machine to identify the exact resources. Let's do a quick search using dkNET: by [searching "estrogen receptor beta antibody"](https://scicrunch.org/legacy-niddk/data/source/nif-0000-07730-1/search?q=%22estrogen%20receptor%20beta%20antibody%22\&l=%22estrogen%20receptor%20beta%20antibody%22), there are more than 100 antibodies in the results with the same antibody name. If only the antibody name is cited in a paper or grant, with no identifying tag, there is no viable way for a fellow researcher to know which antibody was specifically used in the mentioned context. This hinders their ability reproduce or further research the experiments cited in the paper or grant. Catalog numbers are sometimes mentioned with the name of an antibody in order to add some kind of specificity. However, these numbers are subject to numerous changes in the information they actually provide. Outside (often financially driven) forces such as the merging of companies, the restructuring of resource stock, or the closing of a certain manufacturer can greatly alter, or render completely inaccurate, the catalog number associated with an antibody at the time it was cited in a publication. The solution lies with RRID, a unique identifier for research resources. Providing uniformity in regards to citation and taking, RRIDs are being adopted by many players involved in reproducibility in the scientific community to [solve the problem](http://www.biocompare.com/reproducibility/) of keeping resources reproducible and identifiable.&#x20;

### Why is using RRIDs important?

RRID is a unique and stable identifier for a single research resource. RRID indicates use of a research resource, not simply a mention. Again, using RRIDs in papers or grants allows researchers to identify the resources used in the studies, and it's a simple way to improve reproducibility and transparency. Use of RRIDs across journals is increasing. As of August, 2017, hundreds of journals request RRID citation to help fulfill NIH's guidelines for [rigor and reproducibility](https://grants.nih.gov/reproducibility/index.htm). These journals include: Endocrine Society journals such as Journal of Endocrinology, American Journal of Physiology Gastrointestinal and Liver Physiology, Steroid Biochemistry and Molecular Biology, Journal of Hepatology, PNAS, The American Journal of Human Genetics, Cellular Signaling, Elsevier journals, BMC such as BMC Urology, Frontiers, Cell Press, eLife, and Wiley...etc.

Below: Number of journals per publisher using RRIDs (August, 2017):

![](https://dknet.org/upload/community-components/Screen%20Shot%202017-08-24%20at%203_7f6ffaa6bb0b4080.41)

[Full list of journals using RRIDs](https://drive.google.com/file/d/0BytNXDy_2YwCWkVDMFl2bGZobTA/view?usp=sharing) (August, 2017)

RRID requirements listed in author instruction in Endocrinology: <http://press.endocrine.org/page/endoita>

"Registration of unique resources with RRID (Research Resource Identifiers) is recommended (see  <https://scicrunch.org/resources>). If there are restrictions to the availability of such resources, authors must disclose this to the editors at the time of submission, and include a comment on the restrictions in the Materials and Methods section. The Endocrine Society endorses the philosophy of open exchange of research materials and requires this. The Editors may deny further publication rights in the journal to authors unwilling to abide by these principles."

Here is what RRIDs look like in journals:

![](https://dknet.org/upload/community-components/Endocrinology%20RRID%20example_76dc611d6ebaafc6.jpg)

![](https://dknet.org/upload/community-components/Screen%20Shot%202017-07-28%20at%203_f899139df5e10593.10)

### What can you do with RRIDs and how can dkNET help you?

dkNET provides pipelines and services in regards to RRIDs. Furthermore, dkNET provides the user assistance in find and obtaining RRIDs. RRIDs can be used to identify and track your resource. Additionally you can aggregate data about your resource and generate authentication plans for it. All of these is to help you and scientific community to monitor the health of the scientific food chain.

#### Find an RRID

dkNET makes it easy to find RRIDs by providing a single search portal. Over 25 databases are searched for RRIDs using dkNET technologies. These databases include:&#x20;

* Antibodies: [Antibodyregistry.org ](http://antibodyregistry.org/add)
* Cell lines: [Cellosaurus](http://web.expasy.org/cellosaurus/)&#x20;
* Softwares and tools: [SciCrunch:Registry](https://scicrunch.org/)&#x20;
* Model organism:

Ambystoma -[AGSC](http://www.ambystoma.org/)

Mice - [BCBC](http://www.betacell.org/), [CWRU Cystic Fibrosis Mouse Models](http://corefacilities.case.edu/animal.php), [IMSR](http://www.findmice.org/index.jsp), [MGI](http://www.informatics.jax.org/), [MMRRC](https://www.mmrrc.org/)

Flies - BDSC, [DGGR](https://kyotofly.kit.jp/cgi-bin/stocks/index.cgi), [FlyBase](http://flybase.org/)

Pig - [NSRRC](http://www.nsrrc.missouri.edu/)

Xenopus - [NXR](http://www.mbl.edu/xenopus/)

Rat - [RGD](http://rgd.mcw.edu/), Sperm Stem Cell Libraries for Biological Research

Tetrahymena - [Tetrahymena Stock Center](https://tetrahymena.vet.cornell.edu/)

Worms - [WormBase](http://www.wormbase.org/)

Xiphophorus -[XGSC](http://www.xiphophorus.txstate.edu/)

Zebrafish - [ZFIN](http://zfin.org/), [ZIRC](http://zebrafish.org/zirc/home/guide.php)

#### Method 1. Find RRID at dkNET's Resource Report&#x20;

Search for your resources at Resource Reports and find RRIDs that already exist for your resources. Search tip: use a vendor name and/or catalog number for antibodies and cell lines.

![](https://dknet.org/upload/community-components/Slide1_f2217062e9a397a1.jpeg)

#### Method 2. Use the dkNET Authentication Report feature

In regards to grant submission, if you have a dkNET account, you can create a new authentication report and search for relevant resources using the search bar under "Search for your resources and add them to the report". This is located under Authentication Reports dashboard. After adding your resources, you can always come back to check RRIDs in the report.

![](https://dknet.org/upload/community-components/Find%20RRID%20at%20dkNET%20image_1ff8a7b5dc7a7d1f.jpg)

#### Method 3. Use the Resource Identification Portal

You can also go to [Resource Identification Portal ](https://scicrunch.org/resources)directly to find RRIDs:

* Cell Lines: <https://scicrunch.org/resources/Cell%20Lines/search?q=*>
* Antibodies: <https://scicrunch.org/resources/Antibodies/search?q=>
* Specialty Chemicals: <https://scicrunch.org/resources/about/guidelines#celllines>: we currently do not have RRIDs for specialty chemicals. Please use source, catalog number, and [PubChem CID](https://pubchem.ncbi.nlm.nih.gov/search/#collection=compounds) for resource identification.
* Model Organisms:[ https://scicrunch.org/resources/Organisms/search?q=\*](https://scicrunch.org/resources/Organisms/search?q=*)
* Tools (Software, databases, services): <https://scicrunch.org/resources/Tools/search?q=&l=>

#### Obtain an RRID

If you can not find the RRID for your key resource, please reference these [resource-specific search tips](https://scicrunch.org/resources/about/tips). If you have determined that the resource is not present, here are some suggestions that are provided by the Resource Identification Portal Community in order to help you to register your resource and obtain a unique identifier:

* Cell Lines: <https://scicrunch.org/resources/about/guidelines#celllines>
* Antibodies: <http://antibodyregistry.org/add>
* Model Organisms: <https://scicrunch.org/resources/about/guidelines#organism>
* Tools: suggest a resource to SciCrunch <https://dknet.org/about/resource>

{% hint style="info" %}
Don't hesitate to contact <rii-help@scicrunch.org> if you need any help!
{% endhint %}

#### Use RRIDs to identify resources

When you see a resource cited with an RRID in an article or supplemental grant documents, this means that you can find additional metadata via dkNET about said resources. For example, if you find an antibody resource with the citation of RRID:AB\_10547752, copy and paste "[RRID:AB\_10547752](https://dknet.org/Any/search?q=RRID%3AAB_10547752\&l=RRID%3AAB_10547752)" to the dkNET search bar and search. Upon clicking on the resource name you will see the metadata that can help you to identify this antibody.

![](https://dknet.org/upload/community-components/Metadata%20antibody_6cdd60ea0045eb7a.jpg)

#### Use RRIDs to track resources

RRIDs allow for easy tracking of resources. Furthermore, they allows researchers to find out what other studies used the same resources in the literature. This can help researchers aggregate data across experiments regarding individual organisms and cell lines. This aggregation allows for troubleshooting experiments and communication of problems with research resources. Uniquely, this further allows funding agency to track the impact of their decisions.

![](https://dknet.org/upload/community-components/GOOGLE%20RRID_2b24d495052a8ce6.jpg)

#### Generate an authentication plan

The dkNET team has implemented an automated tool in order to assist grant submitters in generating authentication reports (this tool is in its beta version). In order to use this tool, open a dkNET account now (it's free!). Through integrating with RRID, dkNET allows researchers to find resources in dkNET and to transfer those resources to the individual's named project. dkNET can then generate an authentication report with RRIDs and information used for identification and authentication plan of all the resources in the researcher's project. The researcher can then use this document for grant applications. Other uses of the report could include keeping the document as authentication material for lab or publication use. The Authentication Report dashboard can also alert researchers about known problems with a given resource.

![](https://dknet.org/upload/community-components/Find%20RRID%20at%20dkNET%20image%203_0a09c8844ba8f093.jpg)

#### dkNET + RRID ecosystem helps monitor the health of the scientific food chain!

dkNET constantly updates its data sources in order to provide researchers with relevant information. Additionally, these constant updates provide insight in regards to resources that may be problematic.  The collaboration of dkNET and RRID allows for researchers and reviewers to track research resources before, during, and after the study is conducted and published. In conjunction with researchers benefiting from alerts regarding their resources, reviewers and editors subsequently benefit from alerts in regards to manuscripts and grants that are submitted or reviewed. Additionally, article consumers can track resources that are mentioned in literature.

Including RRIDs in your paper and grant application will only benefit your scientific research. Start including them now! Let's make our science more rigor, reproducible and transparent!

### References

1. Bandrowski A et al. The Resource Identification Initiative: A cultural shift in publishing. Version F1000Res. 2015 May 29 \[revised 2015 Nov 19]; 4(134). doi: [10.12688/f1000research.6555.2](http://dx.doi.org/10.12688/f1000research.6555.2). eCollection 2015. PMID: [26594330](https://www.ncbi.nlm.nih.gov/pubmed/26594330)
2. Bandrowski AE and Martone ME. RRIDs: A simple Step toward Improving Reproducibility through Rigor and Transparency of Experimental Methods. Neuron. 2016 May 4; 90(3): 434-6. [doi: 10.1016/j.neuron.2016.04.030](https://www.cell.com/neuron/fulltext/S0896-6273\(16\)30117-9). PMID: [27151636](https://www.ncbi.nlm.nih.gov/pubmed/27151636)
3. Bandrowski AE. Identifying and tracking research resources using RRIDs: a practical approach. 2017 Presentation slides.


# The RRID Resolver

Information about RRID resolver

## Introduction

The RRID resolver provides the ability to resolve an RRID without the need for an API key. The resolver by default returns information in a structured report.  In addition, results can be retrieved in JSON format.

For example the resolver page for a software tool (fMRIPrep) can be resolved via the following URL: <https://scicrunch.org/resolver/RRID:SCR_016216>

<figure><img src="https://2664757529-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FIFPUklTpgWYMOYnZkrEP%2Fuploads%2FHAmki564TlQfXtYjw68f%2Fimage.png?alt=media&amp;token=70bc6f21-fcf2-4402-ae21-6f70639db025" alt=""><figcaption><p>RRID Resolver Report</p></figcaption></figure>

## Retrieving JSON Metadata for an RRID

## Use the RRID resolver to return metadata in JSON format

<mark style="color:blue;">`GET`</mark> `https://scicrunch.org/resolver/{RRID}.json`

#### Path Parameters

| Name                                   | Type   | Description             |
| -------------------------------------- | ------ | ----------------------- |
| RRID<mark style="color:red;">\*</mark> | String | The RRID being resolved |

{% tabs %}
{% tab title="200: OK RRID Found" %}

{% endtab %}

{% tab title="404: Not Found RRID Not Found" %}

{% endtab %}
{% endtabs %}


# Searching RIN Indices

Introduction to searching the RIN indices

## Introduction

The Resources Information Network (RIN) APIs are provided via an ElasticSearch endpoint.   Simple URL based searches are available via the GET method.  More complex queries can be supplied via the POST method.

### Access to the RIN APIs

Access to the RIN API is provided via an Elasticsearch pass-through.

## Elasticsearch Pass-Through

<mark style="color:green;">`POST`</mark> `https://api.scicrunch.io/elastic/v1/{index}/_search`

The pass-through is accessible at <https://scicrunch.org/api/1/elastic>.  Similar to standard Elasticsearch APIs you must then supply an index and an action.  In this case the index, the type and the search command (\_search).\
\
Documentation on the Elasticsearch Search API is available at <https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search.html>&#x20;

#### Path Parameters

| Name                                    | Type   | Description          |
| --------------------------------------- | ------ | -------------------- |
| index<mark style="color:red;">\*</mark> | String | Production RIN index |

#### Headers

| Name                                     | Type   | Description                         |
| ---------------------------------------- | ------ | ----------------------------------- |
| apikey<mark style="color:red;">\*</mark> | String | Your API key to access the services |

#### Request Body

| Name | Type   | Description     |
| ---- | ------ | --------------- |
| data | String | JSON query body |

{% tabs %}
{% tab title="200: OK Successful request" %}

```json
{
    "took": 23,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {...}
}
```

{% endtab %}

{% tab title="401: Unauthorized No API key supplied" %}

```json
{
    "error": {
        "root_cause": [
            {
                "type": "security_exception",
                "reason": "action [indices:data/read/search] requires authentication",
                "header": {
                    "WWW-Authenticate": [
                        "Bearer realm=\"security\"",
                        "ApiKey",
                        "Basic realm=\"security\" charset=\"UTF-8\""
                    ]
                }
            }
        ],
        "type": "security_exception",
        "reason": "action [indices:data/read/search] requires authentication",
        "header": {
            "WWW-Authenticate": [
                "Bearer realm=\"security\"",
                "ApiKey",
                "Basic realm=\"security\" charset=\"UTF-8\""
            ]
        }
    },
    "status": 401
}
```

{% endtab %}

{% tab title="400: Bad Request API request is malformed" %}

```json
{
    "error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "request [/RIN_Addgene_pr/rin/_search] contains unrecognized parameter: [api_key]"
            }
        ],
        "type": "illegal_argument_exception",
        "reason": "request [/RIN_Addgene_pr/rin/_search] contains unrecognized parameter: [api_key]"
    },
    "status": 400
}
```

{% endtab %}

{% tab title="404: Not Found The index or the uri is incorrect" %}

```json
{
    "error": {
        "root_cause": [
            {
                "type": "index_not_found_exception",
                "reason": "no such index",
                "resource.type": "index_or_alias",
                "resource.id": "RIN_Addgene",
                "index_uuid": "_na_",
                "index": "RIN_Addgene"
            }
        ],
        "type": "index_not_found_exception",
        "reason": "no such index",
        "resource.type": "index_or_alias",
        "resource.id": "RIN_Addgene",
        "index_uuid": "_na_",
        "index": "RIN_Addgene"
    },
    "status": 404
}
```

{% endtab %}

{% tab title="500: Internal Server Error The query is incorrect" %}

```json
{
    "error": {
        "root_cause": [
            {
                "type": "json_parse_exception",
                "reason": "Unexpected character ('=' (code 61)): was expecting a colon to separate field name and value\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@4eccf1fd; line: 5, column: 25]"
            }
        ],
        "type": "json_parse_exception",
        "reason": "Unexpected character ('=' (code 61)): was expecting a colon to separate field name and value\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@4eccf1fd; line: 5, column: 25]"
    },
    "status": 500
}
```

{% endtab %}

{% tab title="403: Forbidden Invalid API key" %}

{% endtab %}
{% endtabs %}

## Elasticsearch Pass-Through

<mark style="color:blue;">`GET`</mark> `https://api.scicrunch.io/elastic/v1/{index}/_search`

The pass-through is accessible at <https://scicrunch.org/api/1/elastic>.  Similar to standard Elasticsearch APIs you must then supply an index and an action.  In this case the index, the type and the URL search query paramter.

\
Documentation on the Elasticsearch Search API is available at <https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search.html>&#x20;

#### Path Parameters

| Name                                    | Type   | Description          |
| --------------------------------------- | ------ | -------------------- |
| index<mark style="color:red;">\*</mark> | String | Production RIN index |

#### Query Parameters

| Name | Type   | Description   |
| ---- | ------ | ------------- |
| q    | String | Search String |

#### Headers

| Name                                     | Type   | Description                         |
| ---------------------------------------- | ------ | ----------------------------------- |
| apikey<mark style="color:red;">\*</mark> | String | Your API key to access the services |

{% tabs %}
{% tab title="200: OK Successful request" %}

{% endtab %}

{% tab title="400: Bad Request API request is malformed" %}

{% endtab %}

{% tab title="401: Unauthorized No API key supplied" %}

{% endtab %}

{% tab title="403: Forbidden Invalid API key" %}

{% endtab %}

{% tab title="404: Not Found The index or the uri is incorrect" %}

{% endtab %}

{% tab title="500: Internal Server Error The query is incorrect" %}

{% endtab %}
{% endtabs %}

### RIN Index Aliases

Management of indices is accomplished via [Elasticsearch aliases](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-aliases.html). The index aliases are provided:

| Index Alias                        | Description                                  |
| ---------------------------------- | -------------------------------------------- |
| RIN\_Tool\_pr                      | Production tools index                       |
| RIN\_Antibody\_pr                  | Production antibodies index                  |
| RIN\_CellLine\_pr                  | Production cell lines index                  |
| RIN\_Organism\_pr                  | Production organisms index                   |
| RIN\_Addgene\_pr,RIN\_DGRC\_\*\_pr | Production plasmids (AddGene & DGRC) indices |
| RIN\_BioSample\_pr                 | Production biosamples index                  |
| RIN\_Protocols\_pr                 | Production protocols index                   |
| \*\_pr                             | Production all indices                       |

Using aliases will allow for testing on updates and enhancements to the  index structure.  If needed additional aliases can be constructed for specialized testing.


# Basic RIN Search Examples

## Simple URL based search

```url
https://api.scicrunch.io/elastic/v1/RIN_Tool_pr/_search?q=SPM
```

The above URL will search the SciCrunch registry for all resources that refer to SPM (a nuroimaging analysis tool). The CURL request for this search would be:

```bash
curl --location 'https://api.scicrunch.io/elastic/v1/RIN_Tool_pr/_search?q=SPM' \
--header 'apikey: <<YOUR API KEY>>'
```

## Search all resources

This search looks for all resources of the current RIN index.

For example, searching all registry resources (Tools).

### JSON Body

```json
{
    "size": 20,
    "from": 0,
    "aggregations": {
        "Resource Type": {
            "terms": {
                "field": "item.types.name.aggregate",
                "size": 200
            }
        },
        "Keywords": {
            "terms": {
                "field": "item.keywords.keyword",
                "size": 200
            }
        },
        "Organism": {
            "terms": {
                "field": "organisms.related.species.name.aggregate",
                "size": 200
            }
        },
        "Related Condition": {
            "terms": {
                "field": "diseases.related.name.aggregate",
                "size": 200
            }
        },
        "Funding Agency": {
            "terms": {
                "field": "supportingAwards.agency.name.aggregate",
                "size": 200
            }
        },
        "Website Status": {
            "terms": {
                "field": "item.status",
                "size": 200
            }
        },
        "Mentions": {
            "terms": {
                "field": "mentions.availability.keyword",
                "size": 200
            }
        }
    }
}
```

### Result

```json
{
    "took": 23,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 22140,
        "max_score": 1.0,
        "hits": [
            {
                "_index": "scr_005400-registry_resources_pr-rin-2022apr21",
                "_type": "rin",
                "_id": "rrid:scr_019389",
                "_score": 1.0,
                "_source": {
                    "item": {
                    ...
}
```

## Search for resources by keywords

This search looks for all resources that match keywords.

For example, searching Cell Line resources with keyword (CVCL\_0030) and Vendor (ATCC).

### JSON Body

```json
{
    "size": 20,
    "from": 0,
    "query": {
        "bool": {
            "must": [
                {
                    "query_string": {
                        "fields": [
                            "vendors.name"
                        ],
                        "query": "\"ATCC\"",
                        "default_operator": "and",
                        "lenient": "true"
                    }
                },
                {
                    "query_string": {
                        "fields": [
                            "*"
                        ],
                        "query": "\"CVCL_0030\"",
                        "type": "cross_fields",
                        "default_operator": "and",
                        "lenient": "true"
                    }
                }
            ],
            "should": [
                {
                    "match": {
                        "item.name": {
                            "query": "\"CVCL_0030\"",
                            "boost": 20
                        }
                    }
                },
                {
                    "term": {
                        "item.name.aggregate": {
                            "term": "CVCL_0030",
                            "boost": 2000
                        }
                    }
                }
            ]
        }
    },
    "aggregations": {
        "Vendor": {
            "terms": {
                "field": "vendors.name.aggregate",
                "size": 200
            }
        },
        "Category": {
            "terms": {
                "field": "item.keywords.keyword",
                "size": 200
            }
        },
        "Disease": {
            "terms": {
                "field": "diseases.host.name.aggregate",
                "size": 200
            }
        },
        "Organism": {
            "terms": {
                "field": "organisms.origin.species.name.aggregate",
                "size": 200
            }
        },
        "References": {
            "terms": {
                "field": "references.curie.aggregate",
                "size": 200
            }
        },
        "Sex": {
            "terms": {
                "field": "attributes.sex.value",
                "size": 200
            }
        },
        "Mentions": {
            "terms": {
                "field": "mentions.availability.keyword",
                "size": 200
            }
        },
        "Issues": {
            "terms": {
                "field": "issues.status",
                "size": 200
            }
        }
    }
}
```

### Result

```json
{
    "took": 11,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 35,
        "max_score": 40.370987,
        "hits": [
            {
                "_index": "scr_013869-cellosaurus_celllines_pr-rin-2022apr27",
                "_type": "rin",
                "_id": "rrid:cvcl_0030-atcc-ccl-2",
                "_score": 40.370987,
                "_source": {
                    "item": {
                        "types": [
                            {
                                "curie": "ilx:0101850",
                                "name": "cell line"
                            },
                            {
                                "type": "supercategory"
                            }
                        ],
                        ...
}
```

## Search for resource by identifier

This search looks for a resource that matches the supplied identifier (RRID#).

For example, searching registry resource, RRID:SCR\_000415

### JSON Body

```
{
    "size": 1000,
    "from": 0,
    "query": {
        "query_string": {
            "fields": [
                "rrid.curie"
            ],
            "query": "RRID\\:SCR_000415"
        }
    }
}
```

### Result

```json
{
    "took": 3,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 12.198048,
        "hits": [
            {
                "_index": "scr_005400-registry_resources_pr-rin-2022apr21",
                "_type": "rin",
                "_id": "rrid:scr_000415",
                "_score": 12.198048,
                "_source": {
                    "item": {
                        "supercategory": [
                            {
                                "name": "Resource",
                                "type": "supercategory"
                            }
                        ],
                        "contentTypes": [
                            {
                                "curie": "ilx:0381348",
                                "name": "product"
                            }
                        ],
                        "language": "en",
                        "description": "A software package for control of automated microscopes that runs as a plugin in ImageJ, works with virtually all scientific grade microscope equipment, and has a simple interface towards routine image acquisition strategies such as time-lapse, z- stacks, multi-channel, and multi-position acquisition. In addition, it uses a device abstraction layer available from various programming environments (such a C, Java, Python, Matlab and LabView), facilitating development of novel approaches to image acquisition. Manager has a simple and clean user interface, through which it lets users execute common microscope image acquisition strategies such as time-lapses, multi-channel imaging, z-stacks, and combinations thereof. Manager works with microscopes from all four major manufacturers (Leica, Nikon, Olympus and Zeiss), most scientific-grade cameras and many peripherals (stages, filter wheels, shutters, etc.) used in microscope imaging.",
                        "identifier": "SCR_000415",
                        "docid": "rrid:scr_000415",
                        "uuid": "eda7a99e-7e65-5055-b407-fd05d417e085",
                        "synonyms": [
                            {
                                "name": "Micro-Manager Open Source Microscopy Software"
                            }
                        ],
                        "types": [
                            {
                                "name": "software application",
                                "type": "category"
                            },
                            {
                                "name": "data processing software",
                                "type": "category"
                            },
                            {
                                "name": "data acquisition software",
                                "type": "category"
                            },
                            {
                                "name": "software resource",
                                "type": "category"
                            }
                        ],
                        "keywords": [
                            {
                                "keyword": "microscopy"
                            },
                            {
                                "keyword": "plugin"
                            },
                            {
                                "keyword": "data acquisition"
                            },
                            {
                                "keyword": "software package"
                            },
                            {
                                "keyword": "automated microscope"
                            }
                        ],
                        "curie": "SCR_000415",
                        "availability": [
                            {
                                "description": "",
                                "keyword": ""
                            }
                        ],
                        "alternateIdentifiers": [
                            {
                                "identifier": ""
                            }
                        ],
                        "abbreviations": [
                            {
                                "name": "Micro-Manager"
                            }
                        ],
                        "name": "Micro-Manager"
                    },
                    "authority": {
                        "name": "SciCrunch Registry"
                    },
                    "distributions": {
                        "current": [
                            {
                                "type": "landing page",
                                "uri": "http://micro-manager.org"
                            }
                        ],
                        "deprecated": [
                            {
                                "uri": ""
                            }
                        ],
                        "alternate": [
                            {
                                "uri": "http://www.nitrc.org/projects/micromanager"
                            }
                        ]
                    },
                    "rrid": {
                        "is_unique": "true",
                        "curie": "RRID:SCR_000415",
                        "properCitation": "Micro-Manager (RRID:SCR_000415)"
                    },
                    "disco": {
                        "v_uuid": "eda7a99e-7e65-5055-b407-fd05d417e085"
                    },
                    "graph": {
                        "parent": [
                            {
                                "resource": {
                                    "identifier": "SCR_010605",
                                    "name": "University of California at San Francisco; California; USA"
                                },
                                "relationship": {
                                    "identifier": "7",
                                    "name": "has_parent_organization"
                                }
                            }
                        ],
                        "related": [
                            {
                                "resource": {
                                    "identifier": "SCR_018680",
                                    "name": "ImageJ"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            }
                        ],
                        "relationships": [
                            {
                                "resource": {
                                    "identifier": "SCR_003430",
                                    "name": "NeuroImaging Tools and Resources Collaboratory (NITRC)"
                                },
                                "relationship": {
                                    "identifier": "4",
                                    "name": "is_listed_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_018680",
                                    "name": "ImageJ"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_010605",
                                    "name": "University of California at San Francisco; California; USA"
                                },
                                "relationship": {
                                    "identifier": "7",
                                    "name": "has_parent_organization"
                                }
                            }
                        ]
                    },
                    "diseases": {
                        "related": [
                            {
                                "role": "Related Disease",
                                "name": ""
                            }
                        ]
                    },
                    "supportingAwards": [
                        {
                            "agency": {
                                "name": ""
                            }
                        }
                    ],
                    "references": [
                        {
                            "curie": ""
                        }
                    ],
                    "organisms": {
                        "related": [
                            {
                                "role": "Related Species",
                                "species": {
                                    "name": ""
                                }
                            }
                        ]
                    },
                    "dataItem": {
                        "dataTypes": [
                            "item",
                            "authority",
                            "distributions",
                            "rrid",
                            "disco",
                            "graph",
                            "diseases",
                            "supportingAwards",
                            "references",
                            "organisms"
                        ]
                    },
                    "provenance": {
                        "ingestMethod": "dkNET",
                        "ingestTarget": "",
                        "filePattern": "",
                        "ingestTime": "20230209T050017+0000",
                        "creationDate": [
                            "20220129T080201+0000"
                        ],
                        "docId": "61f4f47948932023e322e24e",
                        "primaryKey": "SCR_000415"
                    },
                    "mentions": [
                        {
                            "totalResourceMentions": {
                                "count": 229
                            },
                            "availability": {
                                "keyword": "available"
                            },
                            "totalRRIDMentions": {
                                "count": 31
                            },
                            "totalMentions": {
                                "count": 247
                            },
                            "timestamp": "2023-02-09 05:00:17.441"
                        }
                    ]
                }
            }
        ]
    }
}
```

&#x20;


# RIN Elaticsearch JSON Data Model

Below we provide an example of a returned search result from the RIN services.  The following CURL command can be used to test the service and view the response. The result only shows the first&#x20;

```bash
curl --location 'https://api.scicrunch.io/elastic/v1/RIN_Tool_pr/_search?q=SPM' \
--header 'apikey: <<YOUR API KEY>>'
```

```json
{
    "took": 8,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 85,
        "max_score": 12.210579,
        "hits": [
            {
                "_index": "scr_005400-registry_resources_pr-rin-2022apr21",
                "_type": "rin",
                "_id": "rrid:scr_007037",
                "_score": 12.210579,
                "_source": {
                    "item": {
                        "supercategory": [
                            {
                                "name": "Resource",
                                "type": "supercategory"
                            }
                        ],
                        "contentTypes": [
                            {
                                "curie": "ilx:0381348",
                                "name": "product"
                            }
                        ],
                        "language": "en",
                        "description": "Software package for analysis of brain imaging data sequences. Sequences can be a series of images from different cohorts, or time-series from same subject. Current release is designed for analysis of fMRI, PET, SPECT, EEG and MEG.",
                        "identifier": "SCR_007037",
                        "docid": "rrid:scr_007037",
                        "uuid": "c136e372-d264-5603-9eb6-6dba1ef16a39",
                        "synonyms": [
                            {
                                "name": "Statistical Parametric Mapping"
                            },
                            {
                                "name": "Statistical Parametric Mapping Software"
                            },
                            {
                                "name": "SPM"
                            },
                            {
                                "name": "SPM12"
                            },
                            {
                                "name": "SPM8"
                            },
                            {
                                "name": "SPM5"
                            },
                            {
                                "name": "SPM2"
                            },
                            {
                                "name": "SPM99"
                            },
                            {
                                "name": "SPM96"
                            }
                        ],
                        "types": [
                            {
                                "name": "image analysis software",
                                "type": "category"
                            },
                            {
                                "name": "time-series analysis software",
                                "type": "category"
                            },
                            {
                                "name": "data processing software",
                                "type": "category"
                            },
                            {
                                "name": "narrative resource",
                                "type": "category"
                            },
                            {
                                "name": "3d time-series analysis software",
                                "type": "category"
                            },
                            {
                                "name": "license",
                                "type": "category"
                            },
                            {
                                "name": "data or information resource",
                                "type": "category"
                            },
                            {
                                "name": "software application",
                                "type": "category"
                            },
                            {
                                "name": "open-source license",
                                "type": "category"
                            },
                            {
                                "name": "gnu general public license",
                                "type": "category"
                            },
                            {
                                "name": "software resource",
                                "type": "category"
                            },
                            {
                                "name": "mri 3d image",
                                "type": "category"
                            },
                            {
                                "name": "3d spatial image",
                                "type": "category"
                            },
                            {
                                "name": "data analysis software",
                                "type": "category"
                            },
                            {
                                "name": "image",
                                "type": "category"
                            }
                        ],
                        "keywords": [
                            {
                                "keyword": "analysis"
                            },
                            {
                                "keyword": "brain"
                            },
                            {
                                "keyword": "imaging"
                            },
                            {
                                "keyword": "data"
                            },
                            {
                                "keyword": "sequence"
                            },
                            {
                                "keyword": "fMRI"
                            },
                            {
                                "keyword": "PET"
                            },
                            {
                                "keyword": "SPECT"
                            },
                            {
                                "keyword": "EEG"
                            },
                            {
                                "keyword": "MEG"
                            },
                            {
                                "keyword": "bio.tools"
                            }
                        ],
                        "curie": "SCR_007037",
                        "availability": [
                            {
                                "description": "Free, Available for download, Freely available",
                                "keyword": "Free, Available for download, Freely available"
                            }
                        ],
                        "alternateIdentifiers": [
                            {
                                "identifier": "nif-0000-00343"
                            },
                            {
                                "identifier": "biotools:SPM"
                            }
                        ],
                        "abbreviations": [
                            {
                                "name": "SPM"
                            }
                        ],
                        "name": "SPM"
                    },
                    "authority": {
                        "name": "SciCrunch Registry"
                    },
                    "distributions": {
                        "current": [
                            {
                                "type": "landing page",
                                "uri": "https://www.fil.ion.ucl.ac.uk/spm/"
                            }
                        ],
                        "deprecated": [
                            {
                                "uri": ""
                            }
                        ],
                        "alternate": [
                            {
                                "uri": "https://github.com/spm"
                            },
                            {
                                "uri": "https://bio.tools/SPM"
                            }
                        ]
                    },
                    "rrid": {
                        "is_unique": "true",
                        "curie": "RRID:SCR_007037",
                        "properCitation": "SPM (RRID:SCR_007037)"
                    },
                    "disco": {
                        "v_uuid": "c136e372-d264-5603-9eb6-6dba1ef16a39"
                    },
                    "graph": {
                        "parent": [
                            {
                                "resource": {
                                    "identifier": "SCR_011603",
                                    "name": "University College London; London; United Kingdom"
                                },
                                "relationship": {
                                    "identifier": "7",
                                    "name": "has_parent_organization"
                                }
                            }
                        ],
                        "related": [
                            {
                                "resource": {
                                    "identifier": "SCR_002613",
                                    "name": "WFU Biological Parametric Mapping Toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_002619",
                                    "name": "vis: SPM Visualized Statistics toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_002915",
                                    "name": "LEAD-DBS"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_003276",
                                    "name": "CCHMC Pediatric Brain Templates"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_003772",
                                    "name": "IBMA toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_005990",
                                    "name": "ArtRepair for robust fMRI"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_005997",
                                    "name": "ASL data processing tool box"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_007354",
                                    "name": "BrainVISA / Anatomist"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_008264",
                                    "name": "MRIcro Software"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_008642",
                                    "name": "xjView: A Viewing Program For SPM"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009537",
                                    "name": "BrainMagix SPM Viewer"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009605",
                                    "name": "MarsBaR region of interest toolbox for SPM"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009630",
                                    "name": "NIRS-SPM"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009644",
                                    "name": "SPM SS - fMRI functional localizers"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009652",
                                    "name": "Wisconsin White Matter Hyperintensities Segmentation Toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_010465",
                                    "name": "Dementia-specific FDG PET Template for SPM analyses"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_013273",
                                    "name": "SPM Anatomy Toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_007371",
                                    "name": "MIPAV: Medical Image Processing and Visualization"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_001622",
                                    "name": "MATLAB"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_017682",
                                    "name": "hMRI-toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_019279",
                                    "name": "Sandwich Estimator Toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            }
                        ],
                        "relationships": [
                            {
                                "resource": {
                                    "identifier": "SCR_013667",
                                    "name": "Neuroimaging Data Model"
                                },
                                "relationship": {
                                    "identifier": "2",
                                    "name": "uses"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_000868",
                                    "name": "imcalc: SPM batch image calculator"
                                },
                                "relationship": {
                                    "identifier": "2",
                                    "name": "uses"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_016591",
                                    "name": "rsfMRI_fconn calculation"
                                },
                                "relationship": {
                                    "identifier": "2",
                                    "name": "is_used_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_003560",
                                    "name": "Automatic Analysis"
                                },
                                "relationship": {
                                    "identifier": "2",
                                    "name": "is_used_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_018308",
                                    "name": "auto_acpc_reorient"
                                },
                                "relationship": {
                                    "identifier": "2",
                                    "name": "is_used_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_003430",
                                    "name": "NeuroImaging Tools and Resources Collaboratory (NITRC)"
                                },
                                "relationship": {
                                    "identifier": "4",
                                    "name": "is_listed_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_001377",
                                    "name": "3DVC"
                                },
                                "relationship": {
                                    "identifier": "4",
                                    "name": "is_listed_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_006638",
                                    "name": "Debian"
                                },
                                "relationship": {
                                    "identifier": "4",
                                    "name": "is_listed_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_014695",
                                    "name": "bio.tools"
                                },
                                "relationship": {
                                    "identifier": "4",
                                    "name": "is_listed_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_024411",
                                    "name": "SoftCite"
                                },
                                "relationship": {
                                    "identifier": "4",
                                    "name": "is_listed_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_014096",
                                    "name": "Clinical Toolbox for SPM"
                                },
                                "relationship": {
                                    "identifier": "5",
                                    "name": "is_affiliated_with"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_002092",
                                    "name": "Statistical non-Parametric Mapping"
                                },
                                "relationship": {
                                    "identifier": "5",
                                    "name": "is_affiliated_with"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_002613",
                                    "name": "WFU Biological Parametric Mapping Toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_002619",
                                    "name": "vis: SPM Visualized Statistics toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_002915",
                                    "name": "LEAD-DBS"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_003276",
                                    "name": "CCHMC Pediatric Brain Templates"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_003772",
                                    "name": "IBMA toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_005990",
                                    "name": "ArtRepair for robust fMRI"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_005997",
                                    "name": "ASL data processing tool box"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_007354",
                                    "name": "BrainVISA / Anatomist"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_008264",
                                    "name": "MRIcro Software"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_008642",
                                    "name": "xjView: A Viewing Program For SPM"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009537",
                                    "name": "BrainMagix SPM Viewer"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009605",
                                    "name": "MarsBaR region of interest toolbox for SPM"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009630",
                                    "name": "NIRS-SPM"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009644",
                                    "name": "SPM SS - fMRI functional localizers"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_009652",
                                    "name": "Wisconsin White Matter Hyperintensities Segmentation Toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_010465",
                                    "name": "Dementia-specific FDG PET Template for SPM analyses"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_013273",
                                    "name": "SPM Anatomy Toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_007371",
                                    "name": "MIPAV: Medical Image Processing and Visualization"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_001622",
                                    "name": "MATLAB"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_017682",
                                    "name": "hMRI-toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_019279",
                                    "name": "Sandwich Estimator Toolbox"
                                },
                                "relationship": {
                                    "identifier": "6",
                                    "name": "is_related_to"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_011603",
                                    "name": "University College London; London; United Kingdom"
                                },
                                "relationship": {
                                    "identifier": "7",
                                    "name": "has_parent_organization"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_015956",
                                    "name": "MRTool"
                                },
                                "relationship": {
                                    "identifier": "8",
                                    "name": "is_required_by"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_016656",
                                    "name": "TSDiffAna"
                                },
                                "relationship": {
                                    "identifier": "10",
                                    "name": "provides"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_015890",
                                    "name": "ICN_Atlas"
                                },
                                "relationship": {
                                    "identifier": "11",
                                    "name": "has_plug_in"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_015525",
                                    "name": "UManitoba - JHU Functionally Defined Human White Matter Atlas"
                                },
                                "relationship": {
                                    "identifier": "12",
                                    "name": "works_with"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_015523",
                                    "name": "NIAG Addiction Data"
                                },
                                "relationship": {
                                    "identifier": "12",
                                    "name": "works_with"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_015890",
                                    "name": "ICN_Atlas"
                                },
                                "relationship": {
                                    "identifier": "12",
                                    "name": "works_with"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_017281",
                                    "name": "spm_auto_reorient_coregister"
                                },
                                "relationship": {
                                    "identifier": "12",
                                    "name": "works_with"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_019184",
                                    "name": "Computational Anatomy Toolbox for SPM"
                                },
                                "relationship": {
                                    "identifier": "12",
                                    "name": "works_with"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_004849",
                                    "name": "FieldTrip"
                                },
                                "relationship": {
                                    "identifier": "12",
                                    "name": "works_with"
                                }
                            },
                            {
                                "resource": {
                                    "identifier": "SCR_010469",
                                    "name": "POAS4SPM"
                                },
                                "relationship": {
                                    "identifier": "12",
                                    "name": "works_with"
                                }
                            }
                        ]
                    },
                    "diseases": {
                        "related": [
                            {
                                "role": "Related Disease",
                                "name": ""
                            }
                        ]
                    },
                    "supportingAwards": [
                        {
                            "agency": {
                                "name": ""
                            }
                        }
                    ],
                    "references": [
                        {
                            "curie": ""
                        }
                    ],
                    "organisms": {
                        "related": [
                            {
                                "role": "Related Species",
                                "species": {
                                    "name": ""
                                }
                            }
                        ]
                    },
                    "dataItem": {
                        "dataTypes": [
                            "item",
                            "authority",
                            "distributions",
                            "rrid",
                            "disco",
                            "graph",
                            "diseases",
                            "supportingAwards",
                            "references",
                            "organisms"
                        ]
                    },
                    "provenance": {
                        "ingestMethod": "dkNET",
                        "ingestTarget": "",
                        "filePattern": "",
                        "ingestTime": "20240205T050425+0000",
                        "creationDate": [
                            "20220129T080239+0000"
                        ],
                        "docId": "626c3a019473880b77dc0164",
                        "primaryKey": "SCR_007037",
                        "lastSeenDate": "20240205T050056+0000"
                    },
                    "mentions": [
                        {
                            "totalResourceMentions": {
                                "count": 7415
                            },
                            "availability": {
                                "keyword": "available"
                            },
                            "totalRRIDMentions": {
                                "count": 311
                            },
                            "totalMentions": {
                                "count": 7508
                            },
                            "timestamp": "2024-02-05 05:04:52.352"
                        }
                    ],
                    "organization": {
                        "hierarchy": {}
                    },
                    "recordValid": true
                }
            },

```


# Download Larger Datasets

If you are new to our API service, we recommend starting with “[Getting Started with the APIs](https://docs.scicrunch.io/api-service-gateway-overview/getting-started-with-sparc-apis)” and “[Using your API key](https://docs.scicrunch.io/api-service-gateway-overview/using-your-api-key)” for helpful guidance first. If you have any questions, please do not hesitate to contact us.\
\
With a large number of records to download you would not be able to do that via a simple Elasticsearch search as Elasticsearch's paging limit is 10,000 records. Therefore, you need to use Elasticsearch's scroll mechanism. \
\
**Initialize Download of an Entire Index**\
\
To download an entire index from the API, you start the scrolling process with the following curl command:

`curl --location 'https://api.scicrunch.io/elastic/v1/<<YOUR TARGET INDEX>>/_search?scroll=1s' \`\
`--header 'Content-Type: application/json' \`\
`--header 'apikey: <<YOUR API KEY>>' \`\
`--data '{ <<YOUR QUERY HERE>> }'`\
\
Make sure to replace the placeholders:

<\<YOUR TARGET INDEX>> with the index you're targeting.

<\<YOUR API KEY>> with your API key.

<\<YOUR QUERY HERE>> with the specific query you want to execute.

For example queries, refer to the following link:[ Example Queries](https://docs.scicrunch.io/elasticsearch-metadata-services/resource-information-network-rin-services/basic-rin-search-examples).

<br>

**Page Through Index and Download Content**

\
The initial scroll query would yield results such as:\
`{`\
`"_scroll_id": "DnF1ZXJ5VGhlbkZldGNoAgAAAAAF-0fRFkhYNzFBb1loU1dLbVpicWpmSTl3b1EAAAAABftH0hZIWDcxQW9ZaFNXS21aYnFqZkk5d29R",`\
`"took": 19,`\
`"timed_out": false,`\
`"_shards": {`\
`"total": 2,`\
`"successful": 2,`\
`"skipped": 0,`\
`"failed": 0`\
`},`\
`"hits": { ...`\
\
To download additional content you would need to download the next set of results.  To do this,  use the scroll\_id from the prior result and create a new request:\
\
`curl --location 'https://api.scicrunch.io/elastic/v1/_search/scroll' \`\
`--header 'Content-Type: application/json' \`\
`--header 'apikey: <<YOUR API KEY>>' \`\
`--data '{`\
`"scroll" : "1s",`\
`"scroll_id" : "DnF1ZXJ5VGhlbkZldGNoAgAAAAAF-0fRFkhYNzFBb1loU1dLbVpicWpmSTl3b1EAAAAABftH0hZIWDcxQW9ZaFNXS21aYnFqZkk5d29R"`\
`}'`\
\
This will generate a set of results with a **new** scroll\_id. Use this new scroll\_id to generate a new request and repeat...


# SPARC Datasets

Overview of SPARC Dataset Services

## Introduction

The SPARC metadata APIs are provided via an ElasticSearch endpoint.  The metadata is extracted from K-Core's metadata export and processed via the FDI Lab's Foundry - a message-oriented, horizontally scalable ETL system for scientific data integration and enhancement (Ozyurt and Grethe 2018).&#x20;

### References

Ozyurt, I. B., & Grethe, J. S. (2018). Foundry: a message-oriented, horizontally scalable ETL system for scientific data integration and enhancement. Database : the journal of biological databases and curation, 2018, bay130. <https://doi.org/10.1093/database/bay130>


# Searching SPARC Dataset Indices

## Introduction

The SPARC metadata APIs are provided via an ElasticSearch endpoint.  &#x20;

### Access to the metadata APIs

Access to the metadata API is provided via an Elasticsearch pass-through.

## Elasticsearch Pass-Through

<mark style="color:green;">`POST`</mark> `https://api.scicrunch.io/elastic/v1/SPARC_Algolia_pr/_search`

The pass-through is accessible at <https://scicrunch.org/api/1/elastic>.  Similar to standard Elasticsearch APIs you must then supply an index and an action.  In this case the SPARC Portal Dataset metadata (SPARC\_Algolia\_pr) and the search command (\_search).\
\
Documentation on the Elasticsearch Search API is available at <https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search.html&#x20>;

#### Path Parameters

| Name                                    | Type   | Description                                   |
| --------------------------------------- | ------ | --------------------------------------------- |
| index<mark style="color:red;">\*</mark> | String | For SPARC datasets this is SPARC\_Algolia\_pr |

#### Headers

| Name                                     | Type   | Description                         |
| ---------------------------------------- | ------ | ----------------------------------- |
| apikey<mark style="color:red;">\*</mark> | String | Your API key to access the services |

#### Request Body

| Name | Type   | Description     |
| ---- | ------ | --------------- |
| data | String | JSON query body |

{% tabs %}
{% tab title="200: OK Successful response" %}

{% endtab %}
{% endtabs %}

## Elasticsearch Pass-Through

<mark style="color:blue;">`GET`</mark> `https://api.scicrunch.io/elastic/v1/SPARC_Algolia_pr/_search`

The pass-through is accessible at <https://scicrunch.org/api/1/elastic>.  Similar to standard Elasticsearch APIs you must then supply an index and an action.  In this case the SPARC Portal Dataset metadata (SPARC\_Algolia\_pr) and the search query parameter.\
\
Documentation on the Elasticsearch Search API is available at <https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search.html&#x20>;

#### Path Parameters

| Name                                    | Type   | Description                                   |
| --------------------------------------- | ------ | --------------------------------------------- |
| index<mark style="color:red;">\*</mark> | String | For SPARC datasets this is SPARC\_Algolia\_pr |

#### Query Parameters

| Name | Type   | Description   |
| ---- | ------ | ------------- |
| q    | String | Search string |

#### Headers

| Name                                     | Type   | Description                         |
| ---------------------------------------- | ------ | ----------------------------------- |
| apikey<mark style="color:red;">\*</mark> | String | Your API key to access the services |

{% tabs %}
{% tab title="200: OK Successful response" %}

{% endtab %}
{% endtabs %}

### SPARC metadata indices

Management of indices is accomplished via [Elasticsearch aliases](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-aliases.html). Three index aliases are provided:

| SPARC\_Algolia\_pr | Production index for SPARC datasets |
| ------------------ | ----------------------------------- |

Using aliases will allow for testing on updates and enhancements to the metadata index structure.  If needed additional aliases can be constructed for specialized testing.


# Basic SPARC Search Examples

## Boolean Filter Search

This search finds data given by generating a boolean query across facets. Currently this is also combined with an optional text based search, although this may be removed in future.

### JSON Body example

```yaml
{
  "size": 10,
  "from": 0,
  "query": {
    "query_string": {
      "query": "(Ardell) AND attributes.subject.sex.value:((male) OR (female))  AND anatomy.organ.name.aggregate:((heart))"
    }
  }
}
```

### Result

```yaml
{
    "took": 2070,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 5,
        "max_score": 5.709837,
        "hits": [
            {
                "_index": "scr_017041-sparc_datasets-ks_2021apr28",
                "_type": "ks",
                "_id": "DOI:10.26275/w4my-puqm",
                "_score": 5.709837,
//...
```

## Available Facets Query

This query requests available facets for a given parameter in the 'hits' object.

### JSON Body example

```yaml
{
  "from": 0,
  "size": 0,
  "aggregations": {
    "genotype": {
      "terms": {
        "field": "anatomy.organ.name.aggregate",
        "size": 200,
        "order": [
          {
            "_count": "desc"
          },
          {
            "_key": "asc"
          }
        ]
      }
    }
  }
}
```

### Result

```yaml
{
    "took": 2,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 88,
        "max_score": 0.0,
        "hits": []
    },
    "aggregations": {
        "genotype": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": "heart",
                    "doc_count": 21
                },
//...
```

## Search for all DOI

This search looks for all DOIs.

### JSON Body Example

```yaml
{
    "from": 0,
    "size": 0,
    "aggregations": {
        "doi" : {
            "composite": {
                "size": 1000,
                "sources": [
                    {
                        "curie": {"terms": {"field": "item.curie.aggregate"}}
                    }
                ],
                "after": {"curie": ""}
            }
        }
    }
```

### Result

```yaml
{
    "took": 31,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 98,
        "max_score": 0.0,
        "hits": []
    },
    "aggregations": {
        "doi": {
            "after_key": {
                "curie": "doi:10.26275/zxe9-o3ss"
            },
            "buckets": [
                {
                    "key": {
                        "curie": "doi:10.26275/0ag5-j3x7"
                    },
                    "doc_count": 1
                }, ...
```

## Search for dataset by title

This search looks for a dataset by title.

### JSON Body Example

```yaml
{
    "size": 20,
    "from": 0,
    "query": {
        "query_string": {
            "fields": [
                "item.names.name"
            ],
            "query": "(Generic) AND (rat) AND (stomach) AND (scaffold)"
        }
    }
}
```

### Result

```yaml
{
    "took": 22,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 7.7667675,
        "hits": [
            {
                "_index": "scr_017041-sparc_portal-ks-2021jun22",
                "_type": "ks",
                "_id": "DOI:10.26275/dn1d-owj9",
                "_score": 7.7667675,
                "_source": {
                    "item": {
                        "version": {
                            "keyword": "1.1.2"
                        },
                        "types": [
                            {
                                "curie": "ilx:0102834",
                                "name": "Dataset",
                                "type": "category"
                            }
                        ],
                        "contentTypes": [
                            {
                                "curie": "ilx:0381348",
                                "name": "product"
                            }
                        ],
                        "names": [
                            {
                                "nameType": "Complete Data Set",
                                "name": "Generic rat stomach scaffold"
                            }
                        ],
                        "statistics": {
                            "files": {
                                "count": "24"
                            },
                            "directory": {
                                "count": "4"
                            },
                            "bytes": {
                                "count": "5582424"
                            }
                        }, ...
```


# SPARC Dataset Elasticsearch JSON Data Model

The data model for results from Elasticsearch is provided below. We provide documentation as "comments" within a trimmed JSON document for a SPARC dataset.

Tarotin, I., Mastitskaya, S., Ravagli, E., holder, david, & Aristovich, K. (2022). Temporal dispersion in porcine subdiaphragmatic nerves ex vivo (Version 1) \[Data set]. SPARC Consortium. <https://doi.org/10.26275/4MFY-Y7BJ>

<pre class="language-json"><code class="lang-json"><strong>### Dataset ID for the returned dataset.  This is part of the core
</strong><strong>### Elasticsearch metadata.  This is an example of one dataset which
</strong><strong>### would be found within the 'hits' for the search
</strong><strong>    "hits": {
</strong>        "total": 250,
        "max_score": 1.0,
        "hits": [
<strong>
</strong><strong>### Elasticsearch document ID which is the SPARC Portal dataset ID
</strong><strong>"_id": "229"
</strong>
### _source contains the return results from Elasticsearch for the dataset
"_source": {

### item contains dataset metadata
    "item": {

### Version information for the JSON results
        "version": {
            "keyword": "1.1.5",
            "description": "Updates for multi-field datacite path information"
        },
        
### The type of datase (e.g. computational model, dataset, ...) 
        "types": [
            {
                "name": "dataset",
                "type": "category"
            }
        ],
 
### Is the object represented informational or something that can be accessed (product)      
        "contentTypes": [
            {
                "curie": "ilx:0381348",
                "name": "product"
            }
        ],

### General statistics about the dataset
        "statistics": {
            "directory": {
                "count": "361"
            },
            "files": {
                "count": "2864"
            },
            "subjects": {
                "count": "7"
            },
            "bytes": {
                "count": "89148729951"
            }
        },
        
### Dataset keywords supplied by the authors
        "keywords": [
            {
                "keyword": "vagus"
            },
        ],
    
### Publication information (published, revision, embargo) 
        "published": {
            "status": "revision",
            "boolean": "true"
        },
        
### Dataset name (title) and description (abstract)
        "dataset": {
            "description": "It includes electrophysiological measurements in response to vagus nerve stimulation taken in swine.",
            "name": "Vagus Nerve Stimulation Mapping in Swine"
        },
    
### Curator notes and additional information about the dataset
        "readme": {
            "description": "**Study Purpose:** To investigate neck muscle responses to vagus nerve stimulation applied at different locations on the vagus nerve.\n\n**Data Collection:** Electrophysiology and electromyography was collected using a Tucker Davis Technology system in swine in response to vagus nerve stimulation.\n\n**Primary Conclusion:** The superior laryngeal branch is activated via current leakage from the stimulation electrode cuff insulation while stimulating caudal to the branching point, and superior laryngeal activation can be avoided by moving the stimulation electrode caudally away from the branch. Activation of the recurrent laryngeal branch fibers, which run under the electrode cuff at all locations in the cervical vagus, cannot be avoided via moving the stimulation electrode. The threshold for activation of the recurrent laryngeal branch fibers could be modulated by hundreds of microamperes, but EMG responses associated with recurrent laryngeal branch fiber activation were always observed before any other response (heart rate or breathing changes) associated with other fiber activation. \n\n---\n\n**Experimental Design:** Intrafascicular electrodes were placed within the vagus nerve to record electroneurographic (ENG) responses, and needle electrodes were placed in the vagal-innervated neck muscles to record electromyographic (EMG) responses. Bipolar stimulation was delivered at 30 Hz using symmetric biphasic pulses with 200 μs per phase and amplitudes from 50 to 3000 μA evaluated in random order. Stimulation was typically delivered for 30 s at each amplitude with at least 1 min rest between trials to allow cardiac responses to return to baseline; in some cases, stimulation was delivered for 3 s at each amplitude with at least 10 s rest due to time constraints.\n\n**Completeness:** Dataset is complete.\n\n**Subjects &#x26; Samples:** Male (n=3) and female (n=4) domestic pigs between 3-4 months of age were used in this study.\n\n**Primary vs derivative data:** Each specific nested data folder nested under primary data (sub-) includes raw electrophysiology recordings organized by individual session subfolders. Parameters of the individual sessions can be found in the performances.xlsx file. There is no derivative data folder.\n\n**Code Availability:** Source Matlab code used to analyze all the electrophysiology and electromyography data are provided in the code folder. Use the notes files in the \"docs\" folder to understand entries into the code. There are multiple tabs (bottom right in excel) for each notes file."
        },
        
### Dataset name (potentially short display title)
        "name": "Vagus nerve stimulation mapping in swine",
        
### Pennsieve dataset identifier (UUID)
        "identifier": "N:dataset:2b9d01f8-41a5-47f9-9168-e809edcae6cb",
        
### Persistent identifier for the dataset (DOI)
        "curie": "DOI:10.26275/qw1u-zxea",
        
### Experimental modalities utilized by the dataset
        "modalities": [
            {
                "keyword": "physiology"
            },
        ],
        
### Document ID to be used for indexing document (corresponds to Portal dataset ID)
        "docid": "229",
        "description": "VNS evoked vagus nerve compound action potential and neck muscle electromyography data via stimulation at a 1 mm disk electrode at many locations on vagus nerve"
    },
    
### Funding information for dataset
    "supportingAwards": [
        {
            "identifier": "OT2OD025340",
            "agency": {
                "name": "National Institutes of Health"
            }
        },
    ],
    

    
### Pennsieve metadata for the dataset
    "pennsieve": {
        "files": {
            "count": "2880"
        },
        "owner": {
            "orcid": {
                "identifier": "0000-0003-0447-568X"
            },
            "identifier": "733",
            "first": {
                "name": "Evan"
            },
            "last": {
                "name": "Nicolai"
            }
        },
        "organization": {
            "identifier": "367",
            "name": "SPARC Consortium"
        },
        "arn": "arn:aws:s3:::pennsieve-prod-discover-publish-use1/229/1/",
        "createdAt": {
            "timestamp": "2022-04-15T20:25:12.512006Z",
            "epoch": "1650054312"
        },
        "uri": "s3://pennsieve-prod-discover-publish-use1/229/1/",
        "status": "PUBLISH_SUCCEEDED",
        "name": "Vagus nerve stimulation mapping in swine",
        "banner": {
            "uri": "https://assets.discover.pennsieve.io/dataset-assets/229/1/revisions/1/banner.png"
        },
        "firstPublishedAt": {
            "timestamp": "2022-04-15T20:25:12.50497Z",
            "epoch": "1650054312"
        },
        "versionPublishedAt": {
            "timestamp": "2022-04-15T20:25:12.512006Z",
            "epoch": "1650054312"
        },
        "license": {
            "keyword": "Creative Commons Attribution"
        },
        "version": {
            "identifier": "1"
        },
        "readme": {
            "uri": "https://assets.discover.pennsieve.io/dataset-assets/229/1/revisions/1/readme.md"
        },
        "sourceDataset": {
            "identifier": "775"
        },
        "identifier": "229",
        "records": {
            "count": "19"
        },
        "updatedAt": {
            "timestamp": "2023-03-08T17:36:15.083356Z",
            "epoch": "1678296975"
        },
        "description": "VNS evoked vagus nerve compound action potential and neck muscle electromyography data via stimulation at a 1 mm disk electrode at many locations on vagus nerve",
        "schemaVersion": {
            "identifier": "4.0"
        },
        "embargo": {
            "keyword": "false"
        },
        "revisedAt": {
            "timestamp": "2022-07-14T21:06:12.832818Z",
            "epoch": "1657832772"
        },
        "revision": {
            "identifier": "1"
        }
    },
    
### Authors for the dataset
    "contributors": [
        {
            "last": {
                "name": "Ludwig"
            },
            "curie": "ORCID:0000-0003-4889-1941",
            "name": "Ludwig, Kip",
            "affiliations": [
                {
                    "description": "Department of Biomedical Engineering, University of Wisconsin-Madison, Madison, WI, United States of America; Department of Neurosurgery, University of Wisconsin-Madison, Madison, WI, United States of America"
                }
            ],
            "uri": "https://orcid.org/0000-0003-4889-1941",
            "first": {
                "name": "Kip"
            }
        },
        
### URI accessible locations for the dataset
    "distributions": {
        "current": [
            {
                "uri": "https://app.pennsieve.io/N:organization:618e8dd9-f8d2-4dc4-9abb-c6aaab2e78a0/datasets/N:dataset:2b9d01f8-41a5-47f9-9168-e809edcae6cb"
            }
        ],
        "api": [
            {
                "uri": "https://api.pennsieve.io/datasets/N:dataset:2b9d01f8-41a5-47f9-9168-e809edcae6cb"
            }
        ]
    },
    
### Published protocols for the dataset available via Protocols.io
    "protocols": {
        "primary": [
            {
                "current": {
                    "uri": "https://www.protocols.io/view/vagus-nerve-stimulation-evoked-electroneurography-bkeyktfw"
                },
                "curie": "DOI:10.17504/protocols.io.bkeyktfw",
                "name": "Vagus Nerve Stimulation Evoked Electroneurography and Electromyography Recordings in Swine",
                "api": {
                    "uri": "https://www.protocols.io/api/v4/protocols/41144"
                }
            }
        ]
    },
    
### Information on organisms involved in the dataset.  This information includes
### identifiers from NCBI taxonomy and the taxonomic hierarchy for the species.
    "organisms": {
    
### All organisms involved in the study
        "subject": [
            {
                "strain": {
                    "name": "Landrace/Yorkshire"
                },
                "species": {
                    "curie": "NCBITaxon:9825",
                    "name": "Domestic Pig",
                    "matchingStatus": "Exact Match",
                    "parents": [
                        {
                            "curie": "ilx:0739765",
                            "name": "Pig"
                        },
                        {
                            "curie": "ilx:0739764",
                            "name": "Sus"
                        },
                    ]
                }
            }
        ],
        
### Primary organism identified for the dataset
        "primary": [
            {
                "species": {
                    "curie": "NCBITaxon:9825",
                    "name": "Domestic Pig",
                    "matchingStatus": "Exact Match",
                    "parents": [
                        {
                            "curie": "ilx:0739765",
                            "name": "Pig"
                        },
                        {
                            "curie": "ilx:0739764",
                            "name": "Sus"
                        },
                    ]
                }
            }
        ]
    },
    
### Attributes of the research subjects that are a part of the dataset.
### This is aggregated across all subjects in the dataset.
    "attributes": {
        "subject": {
            "sex": [
                {
                    "value": "male"
                },
                {
                    "value": "female"
                }
            ],
            "ageCategory": [
                {
                    "value": "adolescent"
                }
            ]
        }
    },
        
### Timestamp(s) for the dataset
    "dates": {
        "created": {
            "timestamp": "2020-07-21T23:45:49,414413Z"
        },
        "updated": [
            {
                "timestamp": "2023-05-12T20:03:14Z"
            }
        ]
    },
    
### Information for anatomical entity(s) represented in the dataset 
    "anatomy": {
        "organ": [
            {
                "curie": "UBERON:0001759",
                "name": "vagus nerve",
                "matchingStatus": "Exact Match"
            }
        ]
    },
    
### Internal processing information for the Elasticsearch document
    "provenance": {
        "ingestMethod": "WEB",
        "ingestTarget": "file:///var/data/data-cache/SCR_017041-SPARC_Datasets-KS/cleaned",
        "filePattern": "^NORM-MANIFEST-NORM-PENNSIEVE-\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}\\.json$",
        "ingestTime": "20230517T012524+0000",
        "creationDate": [
            "20230517T012459+0000"
        ],
        "docId": "64642ceb93879a3172d262f2",
        "primaryKey": "N:dataset:2b9d01f8-41a5-47f9-9168-e809edcae6cb"
    }
}
</code></pre>

},


# InterLex

## Introduction

InterLex (<https://interlex.org>) is a dynamic lexicon, initially built on the foundation of NeuroLex ([PMID: 24009581](https://pubmed.ncbi.nlm.nih.gov/24009581/)), of biomedical terms and common data elements designed to help improve the way that biomedical scientists communicate about their data, so that information systems like the Neuroscience Information Framework (neuinfo.org) and the the Stimulating Peripheral Activity to Relieve Conditions (SPARC) can find data more easily and provide more powerful means of integrating data across distributed resources and datasets. One of the challenges for data integration and FAIR data (Findable, Accessible, Interoperable and Reusable) is the inconsistent use of terminology and data elements. InterLex allows for the association of data fields and data values to common data elements and terminologies enabling the crowdsourcing of data-terminology mappings within and across communities. InterLex provides a stable layer on top of the many other existing terminologies, lexicons, ontologies, and common data element collections and provides a set of inter-lexical and inter-data-lexical mappings.


# Searching InterLex

## Introduction

The InterLex APIs are provided via an ElasticSearch endpoint.  &#x20;

### Access to the InterLex APIs

Access to the InterLex API is provided via an Elasticsearch pass-through.

## Elasticsearch Pass-Through

<mark style="color:green;">`POST`</mark> `https://api.scicrunch.io/elastic/v1/Interlex_pr/_search`

The pass-through is accessible at <https://scicrunch.org/api/1/elastic>.  Similar to standard Elasticsearch APIs you must then supply an index and an action.  In this case the Interlex index (Interlex\_pr) and the search command (\_search).\
\
Documentation on the Elasticsearch Search API is available at <https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search.html&#x20>;

#### Path Parameters

| Name                                    | Type   | Description                       |
| --------------------------------------- | ------ | --------------------------------- |
| index<mark style="color:red;">\*</mark> | string | For InterLex this is Interlex\_pr |

#### Headers

| Name                                     | Type   | Description                         |
| ---------------------------------------- | ------ | ----------------------------------- |
| apikey<mark style="color:red;">\*</mark> | String | Your API key to access the services |

#### Request Body

| Name | Type   | Description     |
| ---- | ------ | --------------- |
| data | String | JSON query body |

{% tabs %}
{% tab title="200 " %}

```
{
    "took": 35,
    "timed_out": false,
    "_shards": {
        "total": 2,
        "successful": 2,
        "skipped": 0,
        "failed": 0
    },
    "hits": {...
```

{% endtab %}
{% endtabs %}

## Elasticsearch Pass-Through

<mark style="color:blue;">`GET`</mark> `https://api.scicrunch.io/elastic/v1/Interlex_pr/_search`

The pass-through is accessible at <https://scicrunch.org/api/1/elastic>.  Similar to standard Elasticsearch APIs you must then supply an index and an action.  In this case the Interlex index (Interlex\_pr) and the search command (\_search).\
\
Documentation on the Elasticsearch Search API is available at <https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search.html&#x20>;

#### Path Parameters

| Name                                    | Type   | Description                       |
| --------------------------------------- | ------ | --------------------------------- |
| index<mark style="color:red;">\*</mark> | String | For InterLex this is Interlex\_pr |

#### Query Parameters

| Name | Type   | Description   |
| ---- | ------ | ------------- |
| q    | String | Search String |

#### Headers

| Name                                     | Type   | Description                         |
| ---------------------------------------- | ------ | ----------------------------------- |
| apikey<mark style="color:red;">\*</mark> | String | Your API key to access the services |

### Interlex indices

Management of indices is accomplished via [Elasticsearch aliases](https://www.elastic.co/guide/en/elasticsearch/reference/6.8/indices-aliases.html). The index aliases are provided:

| Index Alias  | Description               |
| ------------ | ------------------------- |
| Interlex\_pr | Production Interlex index |

Using aliases will allow for testing on updates and enhancements to the  index structure.  If needed additional aliases can be constructed for specialized testing.


# Basic Interlex Search Example

## Search for term by identifier

This search looks for a term that matches the supplied identifier

### JSON Body

```json
{
    "size": 20,
    "from": 0,
    "query": {
    	"bool": {
    	    "must": [ {
		"match_phrase": {
		    "existing_ids.curie": {
		    "query": "NCBITaxon:9606"
		    }
	        }
	    } ]
        }
    }
}
```

### Result

```json
{
    "took": 2,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 19.45221,
        "hits": [
            {
                "_index": "interlex_2019nov01",
                "_type": "term",
                "_id": "ilx_0105114",
                "_score": 19.45221,
                "_source": {
                    "ilx": "ilx_0105114",
                    "label": "Human",
                    "definition": "A mammal of the primate order and genus homo.",
                    "comment": "",
                    "type": "term",
                    "status": "0",
                    "synonyms": [
                        {
                            "literal": "homo sapien",
                            "type": ""
                        },
                        {
                            "literal": "homo sapiens",
                            "type": ""
                        },
                        {
                            "literal": "man",
                            "type": ""
                        }
                    ],
                    "existing_ids": [
                        {
                            "curie": "BIRNLEX:516",
                            "iri": "http://uri.neuinfo.org/nif/nifstd/birnlex_516",
                            "preferred": "0"
                        },
                        {
                            "curie": "ILX:0105114",
                            "iri": "http://uri.interlex.org/base/ilx_0105114",
                            "preferred": "0"
                        },
                        {
                            "curie": "NCBITaxon:9606",
                            "iri": "http://purl.obolibrary.org/obo/NCBITaxon_9606",
                            "preferred": "1"
                        },
                        {
                            "curie": "GBIF:102481489",
                            "iri": "http://www.gbif.org/species/102481489",
                            "preferred": "0"
                        }
                    ],
                    "superclasses": [
                        {
                            "ilx": "ilx_0105088",
                            "label": "Homo"
                        }
                    ],
                    "ancestors": [
                        {
                            "ilx": "ilx_0105088",
                            "label": "Homo"
                        },
                        {
                            "ilx": "ilx_0105089",
                            "label": "Homo Pan Gorilla group"
                        },
                        {
                            "ilx": "ilx_0105086",
                            "label": "Hominidae"
                        },
                        {
                            "ilx": "ilx_0105087",
                            "label": "Hominoidea"
                        },
                        {
                            "ilx": "ilx_0101695",
                            "label": "Catarrhini"
                        },
                        {
                            "ilx": "ilx_0110627",
                            "label": "Simiiformes"
                        },
                        {
                            "ilx": "ilx_0104889",
                            "label": "Haplorrhini"
                        },
                        {
                            "ilx": "ilx_0109341",
                            "label": "Primate"
                        },
                        {
                            "ilx": "ilx_0103972",
                            "label": "Euarchontoglires"
                        },
                        {
                            "ilx": "ilx_0103988",
                            "label": "Eutheria"
                        },
                        {
                            "ilx": "ilx_0111679",
                            "label": "Theria"
                        },
                        {
                            "ilx": "ilx_0106498",
                            "label": "Mammal"
                        },
                        {
                            "ilx": "ilx_0100551",
                            "label": "Amniota"
                        },
                        {
                            "ilx": "ilx_0111643",
                            "label": "Tetrapoda"
                        },
                        {
                            "ilx": "ilx_0110340",
                            "label": "Sarcopterygii"
                        },
                        {
                            "ilx": "ilx_0103987",
                            "label": "Euteleostomi"
                        },
                        {
                            "ilx": "ilx_0111564",
                            "label": "Teleostomi"
                        },
                        {
                            "ilx": "ilx_0104698",
                            "label": "Gnathostomata"
                        },
                        {
                            "ilx": "ilx_0112412",
                            "label": "Vertebrata"
                        },
                        {
                            "ilx": "ilx_0102612",
                            "label": "Craniata"
                        },
                        {
                            "ilx": "ilx_0102135",
                            "label": "Chordata"
                        },
                        {
                            "ilx": "ilx_0103158",
                            "label": "Deuterostomia"
                        },
                        {
                            "ilx": "ilx_0102337",
                            "label": "Coelomata"
                        },
                        {
                            "ilx": "ilx_0101278",
                            "label": "Bilateria"
                        },
                        {
                            "ilx": "ilx_0103978",
                            "label": "Eumetazoa"
                        },
                        {
                            "ilx": "ilx_0106844",
                            "label": "Metazoa"
                        },
                        {
                            "ilx": "ilx_0103976",
                            "label": "Eukaryota"
                        },
                        {
                            "ilx": "ilx_0108133",
                            "label": "Organism"
                        },
                        {
                            "ilx": "ilx_0106552",
                            "label": "Material entity"
                        },
                        {
                            "ilx": "ilx_0105405",
                            "label": "Independent continuant"
                        },
                        {
                            "ilx": "ilx_0102514",
                            "label": "Continuant"
                        }
                    ],
                    "relationships": [],
                    "annotations": [
                        {
                            "term_ilx": "ilx_0105114",
                            "term_label": "Human",
                            "annotation_term_ilx": "ilx_0381360",
                            "annotation_term_label": "hasDbXref",
                            "value": "http://neurolex.org/wiki/birnlex_516"
                        }
                    ],
                    "ontologies": [
                        {
                            "url": "https://raw.githubusercontent.com/tgbugs/nlxeol/master/neurolex_full.csv"
                        }
                    ]
                }
            }
        ]
    }
}
```


# Bulk Add

Simplified example of bulk add for InterLex terms.

## Prerequisite code

With `gspread`, you can automate various tasks such as retrieving and updating tabular data, clearing sheets, and handling multiple tabs within a Google Sheet. This can significantly streamline workflows involving InterLex terms.`gspread` is a powerful tool for interacting with Google Sheets, allowing users to add and update InterLex terms efficiently. It offers functionality to open, modify, and manage Google Sheets using Python, making it easier to handle data programmatically.&#x20;

All the needed code for gspread is found below:

<pre class="language-python"><code class="lang-python"><strong>import gspread 
</strong><strong>
</strong><strong>class GSheet:
</strong>    """Can Opens/Modify Google sheets 1 tab at a time :D"""

    def __init__(self, sheet_name: str) -> None:
        gc = gspread.oauth()
        self.sheet_name = sheet_name
        try:
            self.sheet = gc.open(sheet_name)
        except:
            self.sheet = gc.open_by_key(sheet_name)

    def get_tab(self, tab_name: str) -> pd.DataFrame:
        """
        Get Google Sheet tab as a pandas DataFrame

        Parameters
        ----------
        tab_name : str
            Specific Google Sheet tab name (Google has the default to "Sheet1")

        Returns
        -------
        pd.DataFrame
        """
        worksheet = self.sheet.worksheet(tab_name)
        try:
            header, *body = worksheet.get_all_values()
            return pd.DataFrame(body, columns=header)
        except:  # worksheet is empty
            return pd.DataFrame()

    def update_tab(
        self,
        tab_name: str,
        df: pd.DataFrame,
        cell_range: str = None,
        include_header: bool = True,
    ) -> None:
        """
        Updates only the text of a single tab within the Google Sheet initialized. This does not update the
        Google Sheet settings, colors, fonts, or funcitons. Just the text value.

        Parameters
        ----------
        tab_name : str
            Google Sheet tab name
        df : pd.DataFrame
            DataFrame of the data to be completely overwritten on the tab
        """
        worksheet = self.sheet.worksheet(tab_name)
        if include_header:
            data = [df.columns.values.tolist()] + df.values.tolist()
        else:
            data = df.values.tolist()
        if cell_range:
            worksheet.update(cell_range, data)
        else:
            worksheet.update(data)
            
    def clear(self, tab_name: str) -> None:
        """deletes contents of sheet"""
        worksheet = self.sheet.worksheet(tab_name)
        worksheet.clear()         
</code></pre>

## Gspread Usage

Gspread should be unique in naming scheme in order to avoid using ID hashes for the input.

```python
gsheet = GSheet('Google Sheet Name')
df = gsheet.get_tab('Sheet1')
```

## Curate new Terms

With the string\_profiler function you can `clean` the existing labels with parenthesis for special &#x20;

```python
def string_profiler(
        string: str,
        start_delimiter: str='(',
        end_delimiter: str=')',
        remove: bool=True,
        keep_delimiter: bool = True,
    ) -> List[str]:
    '''
    Seperates strings fragements into list based on the start and end delimiters
    Args:
        string: complete string you want to be broken up based on start and stop delimiters given
        start_delimiter: delimiter element to start
        end_delimiter: delimiter elemtent to end
        remove: decide whether or not to keep strings inside the delimiters
    Returns:
        List[str]: list of strings that are split at start and end delimiters given and whether
            or not you want to remove the string inside the delimiters
    Tests:
        long = '(life is is good) love world "(blah) blah" "here I am" once again "yes" blah '
        print(string_profiler(long))
        null = ''
        print(string_profiler(null))
        short = '(life love) yes(and much more)'
        print(string_profiler(short))
        short = 'yes "life love"'
        print(string_profiler(short))
    '''
    outer_index  = 0  # stepper for outer delimier string elements
    inner_index  = 0  # stepper for inner delimier string elements
    curr_index   = 0  # actual index of the current element in the string
    string_list  = [] # string broken up into individual elements whenever a start and end delimiter is hit
    outer_string = '' # string tracked while outside the delimiters
    inner_string = '' # string tracked while inside the delimiters

    for outer_index in range(len(string)):
        # Actual pointer position (inner delimiter counter + outer delimiter counter)
        curr_index = inner_index + outer_index
        # Close once acutal index is at the end
        # NOTE: outer_index will keep going till end regardless of hitting a delimiter and adding to inner stepper.
        if curr_index == len(string): break
        ### DELIMITER HIT ###
        if string[curr_index] == start_delimiter:
            # If we his a delimiter, collect the string previous to that as an element; flush
            if outer_string:
                # Option: .extend(outer_string.strip().split()) | If you want every word seperate. Maybe an option?
                string_list.append(outer_string.strip())
                outer_string = ''
            for j in range(curr_index+1, len(string)):
                # Stepper that is pushed while in inner delimiter string.
                inner_index += 1
                # Once we his the end delimiter, stop iterating through the inner delimiter string
                if string[j] == end_delimiter: break
                # String inside delimiters
                inner_string += string[j]
            # If you want the string inside the delimiters
            if not remove:
                if keep_delimiter:
                    inner_string = start_delimiter + inner_string + end_delimiter
                string_list.append(inner_string)
            # inner delimiter string restart
            inner_string = ''
        # String outside of the delimiters
        else: outer_string += string[curr_index]
        # End delimiter is either nested or not the real target; should ignore
        if string[curr_index] == end_delimiter:
            if string_list and outer_string:
                string_list[-1] += outer_string
                outer_string = ''
    # In case of not hiting a delimiter at the end of the string, collect the remaining outer delimiter string
    # Option: .extend(outer_string.strip().split()) | If you want every word seperate. Maybe an option?
    if outer_string: string_list.append(outer_string.strip())
    return string_list
```

## Cleaned label column

```python
df['cleaned_label'] = df['label'].apply(lambda x: ''.join(string_profiler(x)).lower())
```

## (Optional) Add Synonyms

Synonyms can be inferred as labels for exact ontology types. If you want to check synonyms for a data source you know is not unique, add as so.

<pre class="language-python"><code class="lang-python"><strong>if isinstance((df['Synonyms'].applymap(type) == list).all():
</strong><strong>    df['Synonyms'] = df.explode('Synonyms')
</strong><strong>
</strong><strong>df['cleaned_synonyms'] = df['Synonyms'].apply(lambda x: ''.join(string_profiler(x)).lower())
</strong></code></pre>

## Add Terms and update Google tab

```python
ilx_id_column = 'ILX UUID'

for i, row in df.iterrows():
    entity_field = row.to_dict()
    
    if 'interlex' in row[ilx_id_column]:
        continue
    elif not row['cleaned_label']:
        continue
    elif row['cleaned_label'] in cleaned_labels: 
        print('row:', row.name + 2, ' -- ', row['cleaned_label'], ['http://uri.interlex.org/base/' + ilx for ilx in label2ilx[row['cleaned_label']]])
        continue
    
    df.loc[i, ilx_id_column] = ilx_cli.add_entity(label=row['label'].strip(), type='term', definition=row['Definition'], **entity_fields)['ilx']
```

## Update Google Tabe

<mark style="color:red;">! Warning !</mark> Please make sure that there is an existing 'ILX UUID' column in the sheet to write over or it will append the column and might remove the annotation meaning such as colors and grouped sets made on the Google sheets.

```python
gsheet.update_tab(df=df, tab_name='Sheet1')
```


# Bulk Update

Simplified example of bulk update for InterLex terms.

## Prerequisite code

Please see [Bulk Add](https://docs.scicrunch.io/terminology-services/interlex/bulk-add)for all prequisite code

## Bulk Update

```python
from ontquery.interlex import interlex_client 
from ilxutils.sql import production_sql

# from_backup=True only avaliable if used cmd `backup_ilx` once ilxutils was installed
sql = production_sql(from_backup=True)


terms = sql.get_terms()
syn = sql.get_synonyms()
annotations = sql.get_annotations()
ex = sql.get_existing_ids()
superclass = sql.get_superclasses()
relationship = sql.get_relationships()

# Client
ilx_cli = interlex_client('scicrunch.org').ilx_cli
```

The docstring for the update\_entity!

```python
ilx_cli = interlex_client('scicrunch.org').ilx_cli

[ out ] ilx_cli.update_entity(
    ilx_id: str,
    label: str = None,
    type: str = None,
    definition: str = None,
    comment: str = None,
    superclass: str = None,
    cid: str = None,
    orig_cid: str = None,
    status: str = None,
    add_synonyms: Union[List[dict], List[str]] = None,
    delete_synonyms: Union[List[dict], List[str]] = None,
    add_existing_ids: List[dict] = None,
    delete_existing_ids: List[dict] = None,
) -> dict
Docstring:
Updates pre-existing entity as long as the api_key is from the account that created it.

:param ilx_id: Interlex IRI, curie, or fragment of entity to update.
:param label: Name of entity.
:param type: InterLex entities type: term, cde, fde, pde, annotation, or relationship
:param definition: Entities official definition.
:param comment: A foot note regarding either the interpretation of the data or the data itself
:param superclass: The ilx_id of the parent of this entity. Example: Organ is a superclass to Brain
:param cid: Community ID.
:param status: Entity status.
    -2 : Withdrawn; entity is no longer searchable and is not visible
    -1 : Under review; entity is visible
    0 : No action needed; entity is visible
:param add_synonyms: Synonyms to add if they don't already exist.
:param delete_synonyms: Synonyms to delete.
:param add_existing_ids: Add alternative IRIs if they don't already exist.
:param delete_existing_ids: Delete alternative IRIs.
:return: Server response that is a nested dictionary format
```


