> This page is for Developer Documentation.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.benchling.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.benchling.com/_mcp/server.

# Interacting with the API using R

Here we'll demonstrate how to interact with the Benchling API using R. To start, let's import some packages:

* `httr`: to send and receive requests to the Benchling API
* `jsonlite`: to help with formatting JSON responses from the API
* `base64enc`: to format the API key correctly

If you're missing these packages you can add them with `install.packages(c("httr", "jsonlite", "base64enc"))`.

## Getting Set Up

In this example, we'll test interacting with the [V3](/docs/v3-api-overview) `/custom-entity` endpoints to perform retrieve, create, update and archive operations. The same principle would work with other API endpoints; just check the details of the request and response formats in the [V3 API reference](https://benchling.com/api/v3/reference).

We'll use our personal API key and store this as an environment variable (`BENCHLING_API_KEY`). For production use cases, we would recommend using a Benchling App: for more on the various authentication options, see the [Authentication](/docs/authentication) guide. We'll create a variable to hold our formatted API key (`auth_key` below) and define some HTTP headers that will form part of the API request:

```r
library(httr)
library(jsonlite)
library(base64enc)

api_key <- Sys.getenv("BENCHLING_API_KEY")
url = "https://TENANT_NAME.benchling.com/api/v3/custom-entity"
auth_key = paste("Basic", base64encode(charToRaw(paste0(api_key, ":"))))
headers = add_headers("Authorization" = auth_key,
                      "Content-Type" = "application/json",
                      "Accept" = "application/json")
```

In V3, the collection and its listing are separate paths: `/custom-entity` is where you create, and `/custom-entity/items` is where you list. We'll build both from `url`.

## Retrieving an Entity

To check if everything works, we'll make a GET request to the API to retrieve a list of custom entities. We'll use the `schema.eq` filter to limit the response to only entities in that schema. To do this, we'll use `httr::GET()` with the URL and headers we defined from the last step:

```r
# Fetch entities from a schema

list_url <- paste(url, "items", sep = "/")

response <- GET(list_url, headers, query = list(schema.eq = "ts_XXXXXX"))
content_txt <- content(response, as = "text", encoding = "UTF-8")
flattened <- fromJSON(content_txt, flatten = TRUE)
entities <- flattened$items
```

> **Info**
>
> **Making nested JSON more table-like**
>
> If you inspect the response you received, you'll notice that the JSON structure is nested. To simplify interacting with the data later on (e.g. via a dataframe) we'll flatten this nested structure and extract the list of entities to a new variable (`entities`).

> **Note**
>
> Two V3 conventions show up in that one call. Results always come back in a field called `items`, where V2 would have named it `customEntities`. And filters carry their operator in the parameter name, so V2's `schemaId` becomes `schema.eq`. See [Filtering](/docs/v3-api-overview#filtering) for the other operators, and note that a page holds 50 results by default; follow `flattened$nextToken` to read the rest.

## Creating an Entity

Now we've successfully retrieved some existing custom entities, we'll try and create a new one using the POST method. To do this will require defining a JSON body to define the fields and metadata for the new entity you wish to create. `POST /api/v3/custom-entity` requires three things: a `name`, the `schemaId` of the schema it belongs to, and the `folderId` of the folder to create it in. To register it at the same time, add the `registryId` of the registry the schema belongs to; a `namingStrategy` of `NEW_IDS` will automatically generate a new registry ID and use the name we've supplied.

To create the necessary structure for `schemaFields`, create a list of field names. To assign a value to the field, nest a second list with the `value` to use for each field. That way, when this is encoded as JSON by `httr` we'll get the correct shape for the API body.

```r
# Create a new entity
body <- list(
  name = "R Thing",
  schemaId = "ts_XXXXXX",
  folderId = "lib_XXXXXX",
  registryId = "src_XXXXXX",
  namingStrategy = "NEW_IDS",
  schemaFields = list(
    "Thing Property" = list(value = "proper property")
    )
  )

response <- POST(url, headers, body = body, encode = "json")
content_txt <- content(response, as = "text", encoding = "UTF-8")
flattened <- fromJSON(content_txt, flatten = TRUE)
```

> **Note**
>
> V2 calls the schema field values `fields`; V3 calls them `schemaFields`. The inner shape is the same, each entry being an object with a single `value` key, so only the outer name changes. V3 also has a separate `customFields` object, which is not the same thing.
>
> The response is shaped differently from the request: there, `schemaFields` is an array of field values, each pairing a `fieldDefinition` reference with its `value`, rather than an object keyed by field.

Inspect the response to check this worked. If it did, you should see the details of the newly registered entity.

## Updating an Entity

So now you've created an entity, how would you go about updating it? To do this we'll use the API ID (this is the `id` in the response) and the PATCH method. Every field is optional on an update, so send only what you want to change.

Let's try to rename the entity we created in the last section. Note that the URL you'll need to use will look like `https://TENANT_NAME.benchling.com/api/v3/custom-entity/ENTITY_API_ID`. Test this by re-naming the entity from the previous step.

```r
# Update an existing entity
patch_url = paste(url, flattened$id, sep = "/")
body <- list(
  name = "Renamed R Thing"
)

response <- PATCH(patch_url, headers, body = body, encode = "json")
content_txt <- content(response, as = "text", encoding = "UTF-8")
flattened <- fromJSON(content_txt, flatten = TRUE)
```

Check the response to see if the name has been updated. As we decided not to include any `schemaFields` in the request body, these will remain unchanged.

## Archiving an Entity

Finally, to wrap things up, archive the entity you just created. In V3 archiving is not a separate action; it is an update. `PATCH` the entity with `archived` set to `TRUE` and an `archiveReason`, using the same `patch_url` as the last section.

Using `Made in error` as our archive reason looks like this:

```r
# Archive an entity
body = list(
  archived = TRUE,
  archiveReason = "Made in error"
  )
response <- PATCH(patch_url, headers, body = body, encode = "json")
content_txt <- content(response, as = "text", encoding = "UTF-8")
flattened <- fromJSON(content_txt, flatten = TRUE)
```

Unarchiving is the same call with `archived = FALSE`.

> **Note**
>
> V2 archives through a bulk action, `POST /api/v2/custom-entities:archive`, taking a list of `customEntityIds` and a `reason`. V3 replaces that with the `archived` and `archiveReason` fields on the resource itself, so single-object archiving is a plain `PATCH`. To archive many at once, use `PATCH /api/v3/custom-entity:batch-update`.
>
> V2 accepted only a fixed set of reason strings, such as `Made in error`. `archiveReason` is an unconstrained string in the V3 spec, so if a value is rejected, check the error response for the reasons your tenant accepts.