Documentation Index
Fetch the complete documentation index at: https://www.1password.dev/llms.txt
Use this file to discover all available pages before exploring further.
You can use 1Password SDKs to read, write, and update secret values stored in your 1Password items.
When managing items, you must use unique identifiers (IDs) in place of vault, item, section, and field names. You can get IDs by listing vaults and items.
You can perform item management operations on supported field types. Some field types have special constraints.
Before you get started
Before you begin, follow the steps to get started with a 1Password SDK. The examples on this page assume you have an initialized client instance, except for password generation, which does not require a client. For example:
package main
import (
"context"
"github.com/1password/onepassword-sdk-go"
)
func main() {
// TODO: Initialize client using your preferred authentication method (see Overview > Get started)
client, err := onepassword.NewClient(context.Background(),
)
if err != nil {
panic(err)
}
// Your code here
}
import sdk from "@1password/sdk";
async function main() {
const client = await sdk.createClient({
// TODO: Initialize client using your preferred authentication method (see Overview > Get started)
});
// Your code here
}
main().catch(console.error);
const sdk = require("@1password/sdk");
async function main() {
const client = await sdk.createClient({
// TODO: Initialize client using your preferred authentication method (see Overview > Get started)
});
// Your code here
}
main().catch(console.error);
import asyncio
from onepassword import Client # Also import DesktopAuth for desktop app authentication.
async def main():
# TODO: Initialize client using your preferred authentication method (see Overview > Get started)
client = await Client.authenticate(...)
# Your code here
asyncio.run(main())
See the examples folder in the 1Password Go, JavaScript, or Python SDK GitHub repository for full example code you can quickly clone and test in your project.
Create an item
To create a new item, specify the parameters for the item and pass the defined item to the Items().Create() method.The following example creates a Login item with a username, password, one-time password, and a website where 1Password will autofill the credentials.The value of the one-time password field can be either a one-time password secret or an otpauth:// URI. In this example, the one-time password field is organized beneath a custom section.sectionID := "extraDetails"
itemParams := onepassword.ItemCreateParams{
Title: "Login created with the SDK",
Category: onepassword.ItemCategoryLogin,
VaultID: vaultID,
Fields: []onepassword.ItemField{
{
ID: "username",
Title: "username",
Value: "Wendy_Appleseed",
FieldType: onepassword.ItemFieldTypeText,
},
{
ID: "password",
Title: "password",
Value: "my_weak_password123",
FieldType: onepassword.ItemFieldTypeConcealed,
},
{
ID: "onetimepassword",
Title: "one-time password",
Value: "otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
SectionID: §ionID,
FieldType: onepassword.ItemFieldTypeTOTP,
},
},
Sections: []onepassword.ItemSection{
{
ID: sectionID,
Title: "Extra Details",
},
},
Tags: []string{"test tag1", "test tag 2"},
Websites: []onepassword.Website{
{
URL: "1password.com",
AutofillBehavior: onepassword.AutofillBehaviorAnywhereOnWebsite,
Label: "my custom website",
},
},
}
// Creates a new item based on the structure definition above
createdItem, err := client.Items().Create(context.Background(), itemParams)
if err != nil {
panic(err)
}
To create a new item, specify the parameters for the item and pass the defined item to the items.create() method.The following example creates a Login item with a username, password, one-time password, and a website where 1Password will autofill the credentials.The value of the one-time password field can be either a one-time password secret or an otpauth:// URI. In this example, the one-time password field is organized beneath a custom section.// Creates an item
let item = await client.items.create({
title: "My Item",
category: sdk.ItemCategory.Login,
vaultId: vaultId,
fields: [
{
id: "username",
title: "username",
fieldType: sdk.ItemFieldType.Text,
value: "my username",
},
{
id: "password",
title: "password",
fieldType: sdk.ItemFieldType.Concealed,
value: "my secret value",
},
{
id: "onetimepassword",
title: "one-time password",
sectionId: "custom section",
fieldType: sdk.ItemFieldType.Totp,
value:
"otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
},
],
sections: [
{
id: "custom section",
title: "my section",
},
],
tags: ["test tag 1", "test tag 2"],
websites: [
{
url: "example.com",
label: "url",
autofillBehavior: sdk.AutofillBehavior.AnywhereOnWebsite,
},
],
});
To create a new item, specify the parameters for the item and pass the defined item to the items.create() method.The following example creates a Login item with a username, password, one-time password, and a website where 1Password will autofill the credentials.The value of the one-time password field can be either a one-time password secret or an otpauth:// URI. In this example, the one-time password field is organized beneath a custom section.from onepassword import (
AutofillBehavior,
ItemCategory,
ItemCreateParams,
ItemField,
ItemFieldType,
ItemSection,
Website,
)
# Create an item
to_create = ItemCreateParams(
title="MyName",
category=ItemCategory.LOGIN,
vault_id="your-vault-id",
fields=[
ItemField(
id="username",
title="username",
field_type=ItemFieldType.TEXT,
value="my-username",
),
ItemField(
id="password",
title="password",
field_type=ItemFieldType.CONCEALED,
value="my-password",
),
ItemField(
id="onetimepassword",
title="one-time-password",
field_type=ItemFieldType.TOTP,
section_id="totpsection",
value="otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
),
],
sections=[
ItemSection(id="", title=""),
ItemSection(id="totpsection", title=""),
],
tags=["test tag 1", "test tag 2"],
websites=[
Website(
label="my custom website",
url="https://example.com",
autofill_behavior=AutofillBehavior.NEVER,
)
],
)
created_item = await client.items.create(to_create)
print(f'Created item "{created_item.title}" ({created_item.id})')
Item parameters
Item parameters include:
| Parameter | Definition |
|---|
Title | The name of the item. |
Category | The type of item you want to create. Supported categories Login, SecureNote, CreditCard, CryptoWallet, Identity, Password, Document, ApiCredentials, BankAccount, Database, DriverLicense, Email, MedicalRecord, Membership, OutdoorLicense, Passport, Rewards, Router, Server, SshKey, SocialSecurityNumber, SoftwareLicense, Person |
Vault ID | The ID of the vault where you want to create the item. |
Fields | The item fields. |
Sections | The item sections. |
Notes | The item notes. |
Tags | A list of tags to add to the item. |
Websites | An optional list of websites where 1Password will suggest and fill the login. Only available for Login and Password items. |
A section organizes fields in an item under a section title. Section parameters include:
| Parameter | Description |
|---|
Section ID | A unique identifier for the section. |
Section Title | The name of the section. |
Field parameters include:
| Parameter | Description |
|---|
ID | A unique identifier for the field. For fields that are specific to an item category, like username and password for a Login item, use the appropriate built-in field ids. |
Title | The name of the field. |
Field type | The type of field. Some field types have special constraints.Supported fields Address, Concealed, CreditCardNumber, CreditCardType, Date, Email, Menu, MonthYear, Notes, Phone, Reference, Text, Totp, Url, SSHKey |
Value | The value stored in the field. |
Field Details | Optional for most field types. Required for Address fields. |
Section ID | Organizes a field under a section. Required for all fields except built-in fields like username and password. If you create a custom field without a section, 1Password will create an empty section and assign the field to it. |
Autofill website parameters include:
| Parameter | Description |
|---|
| URL | The URL for the website. |
| Label | The name of the website. |
| Autofill behavior | When 1Password will autofill your credentials on the website. Options include:
AnywhereOnWebsite: 1Password autofills credentials on any page that’s part of the website, including subdomains. ExactMatch: 1Password autofills credentials only if the domain (hostname and port) is an exact match.Never: 1Password never autofills credentials on this website.
|
Get an item
To get an item, pass the item ID and vault ID for the item to the Items().Get() method.To get the item created in the first step:// Retrieves the newly created item
login, err := client.Items().Get(context.Background(), createdItem.VaultID, createdItem.ID)
if err != nil {
panic(err)
}
To get an item, pass the item ID and vault ID for the item to the items.get() method.To get the item created in the first step:let retrievedItem = await client.items.get(item.vaultId, item.id);
To get an item, pass the item ID and vault ID for the item to the items.get() method.To get an item and print its name and ID:# Get an item
item = await client.items.get("your-vault-id", "your-item-id")
print(f'Retrieved item "{item.title}" ({item.id})')
Get a one-time password
You can use 1Password SDKs to get the value stored in a field, like the six-digit one-time password code from a Totp field.
To retrieve and print a one-time password from the item created in the first step:// Retrieve TOTP code from an item
for _, f := range login.Fields {
if f.FieldType == onepassword.ItemFieldTypeTOTP {
OTPFieldDetails := f.Details.OTP()
if OTPFieldDetails.ErrorMessage == nil {
fmt.Println(*OTPFieldDetails.Code)
} else {
panic(*OTPFieldDetails.ErrorMessage)
}
}
}
To retrieve and print a one-time password from the item created in the first step:// Get a one-time password code.
let element = item.fields.find((element) => {
return element.fieldType == sdk.ItemFieldType.Totp;
});
if (!element) {
console.error("no totp field found on item");
} else {
switch (element.details.type) {
case "Otp": {
if (element.details.content.code) {
console.log(element.details.content.code);
} else {
console.error(element.details.content.errorMessage);
}
}
default:
}
}
item = await client.items.get("your-vault-id", "your-item-id")
# Get a one-time password code from an item
for f in item.fields:
if f.field_type == "Totp":
if f.details.content.error_message is not None:
print(f.details.content.error_message)
else:
print(f.details.content.code)
Update an item
To update an item, fetch the item you want to update, specify the changes you want to make, then pass the updated item to the Items().Put() method.// Retrieves the newly created item
item, err := client.Items().Get(context.Background(), existingVaultID, existingItemID)
if err != nil {
panic(err)
}
// Finds the field named "Details" and edits its value
for i := range item.Fields {
if item.Fields[i].Title == "Details" {
item.Fields[i].Value = "updated details"
}
}
item.Title = "New Title"
item.Websites = append(item.Websites, onepassword.Website{
URL: "2password.com",
Label: "my second custom website",
AutofillBehavior: onepassword.AutofillBehaviorNever,
})
updatedItem, err := client.Items().Put(context.Background(), item)
if err != nil {
panic(err)
}
To update an item, fetch the item you want to update, specify the changes you want to make, then pass the updated item to the items.put() method.// Edit an item (change the password)
let newItem = {
...retrievedItem,
fields: retrievedItem.fields.map((f) => {
if (f.title == "password") {
return { ...f, value: "my-new-password" };
} else {
return f;
}
}),
};
let updatedItem = await client.items.put(newItem);
To update an item, fetch the item you want to update, specify the changes you want to make, then pass the updated item to the items.put() method.from onepassword import AutofillBehavior, Website
item = await client.items.get("your-vault-id", "your-item-id")
# Update an item
item.fields[0].value = "new_value"
item.websites.append(
Website(
label="my custom website 2",
url="https://example2.com",
autofill_behavior=AutofillBehavior.NEVER,
),
)
updated_item = await client.items.put(item)
print(f"Updated item: {updated_item.title} ({updated_item.id})")
Archive an item
To archive an item, pass the item ID and vault ID for the item to the Items().Archive() method.// Archive a item from your vault.
err := client.Items().Archive(context.Background(), vaultID, itemID)
if err != nil {
panic(err)
}
To archive an item, pass the item ID and vault ID for the item to the items.archive() method.// Archive an item from your vault.
await client.items.archive(vaultId, itemId);
To archive an item, pass the item ID and vault ID for the item to the items.archive() method.vault_id = "your-vault-id"
item_id = "your-item-id"
# Archive an item
await client.items.archive(vault_id, item_id)
print(f"Item {item_id} successfully archived from vault {vault_id}.")
Delete an item
To delete an item, pass the item ID and vault ID for the item to the Items().Delete() method.// Delete a item from your vault.
err := client.Items().Delete(context.Background(), vaultID, itemID)
if err != nil {
panic(err)
}
To delete an item, pass the item ID and vault ID for the item to the items.delete() method.// Delete an item from your vault.
await client.items.delete(item.vaultId, item.id);
To delete an item, pass the item ID and vault ID for the item to the items.delete() method.vault_id = "your-vault-id"
item_id = "your-item-id"
# Delete an item
await client.items.delete(vault_id, item_id)
print(f"Item {item_id} successfully deleted from vault {vault_id}.")
Generate a password
You can use the Secrets.GeneratePassword() method to generate a password by passing a PIN, Random, or Memorable password recipe struct, depending on the type of password you want to generate.Generates a PIN code. You can specify the length of the generated code.pinPassword, err := onepassword.Secrets.GeneratePassword(context.Background(), onepassword.NewPasswordRecipeTypeVariantPin(&onepassword.PasswordRecipePinInner{Length: 10}))
if err != nil {
panic(err)
}
fmt.Println(pinPassword.Password)
Generates a random password. You can choose:
- Whether the password includes digits.
- Whether the password includes symbols.
- The length of the password.
randomPassword, err := onepassword.Secrets.GeneratePassword(context.Background(), onepassword.NewPasswordRecipeTypeVariantRandom(&onepassword.PasswordRecipeRandomInner{
IncludeDigits: true,
IncludeSymbols: true,
Length: 10,
}))
if err != nil {
panic(err)
}
fmt.Println(randomPassword.Password)
Generates a memorable password. For example, correct-horse-battery-staple. You can choose:
- The separator used between words. Options:
Spaces, Hyphens, Underscores, Periods, Commas
- Whether the memorable password is made up of full words or random syllables. Options:
FullWords, Syllables, ThreeLetters
- Whether to capitalize one section of the generated password.
- The number of words included in the password.
memorablePassword, err := onepassword.Secrets.GeneratePassword(context.Background(), onepassword.NewPasswordRecipeTypeVariantMemorable(&onepassword.PasswordRecipeMemorableInner{
SeparatorType: onepassword.SeparatorTypeCommas,
WordListType: onepassword.WordListTypeFullWords,
Capitalize: true,
WordCount: 10,
}))
if err != nil {
panic(err)
}
fmt.Println(memorablePassword.Password)
You can use the Secrets.generatePassword() method to generate a password by passing a PIN, Random, or Memorable password recipe object, depending on the type of password you want to generate.Generates a PIN code. You can specify the length of the generated code.try {
let pinPassword = sdk.Secrets.generatePassword({
type: "Pin",
parameters: {
length: 8,
},
});
console.log(pinPassword);
} catch (error) {
console.error(error);
}
Generates a random password. You can choose:
- Whether the password includes digits.
- Whether the password includes symbols.
- The length of the password.
try {
let randomPassword = sdk.Secrets.generatePassword({
type: "Random",
parameters: {
includeDigits: true,
includeSymbols: true,
length: 8,
},
});
console.log(randomPassword);
} catch (error) {
console.error(error);
}
Generates a memorable password. For example, correct-horse-battery-staple. You can choose:
- The separator used between words. Options:
Spaces, Hyphens, Underscores, Periods, Commas
- Whether the memorable password is made up of full words or random syllables. Options:
FullWords, Syllables, ThreeLetters
- Whether to capitalize one section of the generated password.
- The number of words included in the password.
try {
let memorablePassword = sdk.Secrets.generatePassword({
type: "Memorable",
parameters: {
separatorType: sdk.SeparatorType.Digits,
capitalize: true,
wordListType: sdk.WordListType.FullWords,
wordCount: 8,
},
});
console.log(memorablePassword);
} catch (error) {
console.error(error);
}
You can use the Secrets.generate_password() method to generate a password by passing a PIN, Random, or Memorable password recipe object, depending on the type of password you want to generate.Generates a PIN code. You can specify the length of the generated code.from onepassword import PasswordRecipePin, PasswordRecipePinInner, Secrets
# Generate a PIN password
pin_password = Secrets.generate_password(
PasswordRecipePin(parameters=PasswordRecipePinInner(length=8))
)
print(pin_password)
Generates a random password. You can choose:
- Whether the password includes digits.
- Whether the password includes symbols.
- The length of the password.
from onepassword import (
PasswordRecipeRandom,
PasswordRecipeRandomInner,
Secrets,
)
# Generate a random password
random_password = Secrets.generate_password(
PasswordRecipeRandom(
parameters=PasswordRecipeRandomInner(
length=10,
includeDigits=False,
includeSymbols=False,
)
),
)
print(random_password)
Generates a memorable password. For example, correct-horse-battery-staple. You can choose:
- The separator used between words. Options:
Spaces, Hyphens, Underscores, Periods, Commas
- Whether the memorable password is made up of full words or random syllables. Options:
FullWords, Syllables, ThreeLetters
- Whether to capitalize one section of the generated password.
- The number of words included in the password.
from onepassword import (
PasswordRecipeMemorable,
PasswordRecipeMemorableInner,
Secrets,
SeparatorType,
WordListType,
)
# Generate a memorable password
memorable_password = Secrets.generate_password(
PasswordRecipeMemorable(
parameters=PasswordRecipeMemorableInner(
separatorType=SeparatorType.UNDERSCORES,
wordListType=WordListType.SYLLABLES,
capitalize=False,
wordCount=3,
)
),
)
print(memorable_password)
Manage items in bulk
Create items
You can use the Items().CreateAll() method to batch create up to 100 items within a single vault. Learn more about field type constraints.The following example creates three example items in the vault specified with the vaultId variable. Make sure to set this variable to the unique identifier for the vault where you want to create the items.sectionID := "extraDetails"
var itemsToCreate []onepassword.ItemCreateParams
for i := 1; i <= 3; i++ {
itemsToCreate = append(itemsToCreate, onepassword.ItemCreateParams{
Title: fmt.Sprintf("Login %d created with the SDK", i),
Category: onepassword.ItemCategoryLogin,
VaultID: vaultID,
Fields: []onepassword.ItemField{
{
ID: "username",
Title: "username",
Value: "Wendy_Appleseed",
FieldType: onepassword.ItemFieldTypeText,
},
{
ID: "password",
Title: "password",
Value: "my_weak_password123",
FieldType: onepassword.ItemFieldTypeConcealed,
},
{
ID: "onetimepassword",
Title: "one-time password",
Value: "otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
SectionID: §ionID,
FieldType: onepassword.ItemFieldTypeTOTP,
},
},
Sections: []onepassword.ItemSection{
{
ID: sectionID,
Title: "Extra Details",
},
},
Tags: []string{"test tag1", "test tag 2"},
Websites: []onepassword.Website{
{
URL: "1password.com",
AutofillBehavior: onepassword.AutofillBehaviorAnywhereOnWebsite,
Label: "my custom website",
},
},
})
}
// Create all items in the same vault in a single batch
batchCreateResponse, err := client.Items().CreateAll(context.Background(), vaultID, itemsToCreate)
if err != nil {
panic(err)
}
var itemIDs []string
for _, res := range batchCreateResponse.IndividualResponses {
if res.Content != nil {
fmt.Printf("Created Item %q (%s)\\n", res.Content.Title, res.Content.ID)
itemIDs = append(itemIDs, res.Content.ID)
} else if res.Error != nil {
fmt.Printf("[Batch create] Something went wrong: %s\\n", res.Error)
}
}
You can use the items.createAll() method to batch create up to 100 items within a single vault. Learn more about field type constraints.The following example creates three example items in the vault specified with the vault.id variable. Make sure to set this variable to the unique identifier for the vault where you want to create the items.itemsToCreate = [];
for (let i = 1; i <= 3; i++) {
itemsToCreate.push({
title: "My Login Item " + i,
category: sdk.ItemCategory.Login,
vaultId,
fields: [
{
id: "username",
title: "username",
fieldType: sdk.ItemFieldType.Text,
value: "my username",
},
{
id: "password",
title: "password",
fieldType: sdk.ItemFieldType.Concealed,
value: "my secret value",
},
{
id: "onetimepassword",
title: "one-time password",
sectionId: "custom section",
fieldType: sdk.ItemFieldType.Totp,
value:
"otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
},
],
sections: [
{
id: "custom section",
title: "my section",
},
],
tags: ["test tag 1", "test tag 2"],
websites: [
{
url: "example.com",
label: "url",
autofillBehavior: sdk.AutofillBehavior.AnywhereOnWebsite,
},
],
});
}
const batchCreateResponse = await client.items.createAll(
vaultId,
itemsToCreate,
);
let itemIDs = [];
for (const res of batchCreateResponse.individualResponses) {
if (res.content) {
console.log(
"Created item",
res.content.title,
"(" + res.content.id + ")",
);
itemIDs.push(res.content.id);
} else if (res.error) {
console.log(
"[Batch create] Something went wrong:",
res.error,
);
}
}
You can use the items.create_all() method to batch create up to 100 items within a single vault. Learn more about field type constraints.The following example creates three example items in the vault specified with the vault_id variable. Make sure to set this variable to the unique identifier for the vault where you want to create the items.from onepassword import (
AutofillBehavior,
ItemCategory,
ItemCreateParams,
ItemField,
ItemFieldType,
ItemSection,
Website,
)
vault_id = "your-vault-id"
items_to_create = []
for i in range(1, 4):
items_to_create.append(
ItemCreateParams(
title="My Login Item {}".format(i),
category=ItemCategory.LOGIN,
vault_id=vault_id,
fields=[
ItemField(
id="username",
title="username",
field_type=ItemFieldType.TEXT,
value="my-username",
),
ItemField(
id="password",
title="password",
field_type=ItemFieldType.CONCEALED,
value="my-password",
),
ItemField(
id="onetimepassword",
title="one-time-password",
field_type=ItemFieldType.TOTP,
section_id="totpsection",
value="otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
),
],
sections=[
ItemSection(id="", title=""),
ItemSection(id="totpsection", title=""),
],
tags=["test tag 1", "test tag 2"],
websites=[
Website(
label="my custom website",
url="https://example.com",
autofill_behavior=AutofillBehavior.NEVER,
)
],
)
)
# Batch create all items in the same vault
batchCreateResponse = await client.items.create_all(vault_id, items_to_create)
item_ids = []
for res in batchCreateResponse.individual_responses:
if res.content is not None:
print('Created item "{}" ({})'.format(res.content.title, res.content.id))
item_ids.append(res.content.id)
elif res.error is not None:
print("[Batch create] Something went wrong: {}".format(res.error))
Get items
You can use the Items().GetAll() method to fetch up to 50 items from a specified vault using their unique identifiers.To get the items you created in the previous step:// Get multiple items form the same vault in a single batch
batchGetResponse, err := client.Items().GetAll(context.Background(), vaultID, itemIDs)
if err != nil {
panic(err)
}
for _, res := range batchGetResponse.IndividualResponses {
if res.Content != nil {
fmt.Printf("Obtained Item %q (%s)\\n", res.Content.Title, res.Content.ID)
} else if res.Error != nil {
fmt.Printf("[Batch get] Something went wrong: %s\\n", res.Error)
}
}
You can use the items.getAll() method to fetch up to 50 items from a specified vault using their unique identifiers.To get the items you created in the previous step:const batchGetResponse = await client.items.getAll(vaultId, itemIDs);
for (const res of batchGetResponse.individualResponses) {
if (res.content) {
console.log(
"Obtained item",
res.content.title,
"(" + res.content.id + ")",
);
} else if (res.error) {
console.log(
"[Batch get] Something went wrong:",
res.error,
);
}
}
You can use the items.get_all() method to fetch up to 50 items from a specified vault using their unique identifiers.vault_id = "your-vault-id"
item_ids = ["your-item-id-1", "your-item-id-2"]
# Get multiple items from the same vault
batchGetReponse = await client.items.get_all(vault_id, item_ids)
for res in batchGetReponse.individual_responses:
if res.content is not None:
print('Obtained item "{}" ({})'.format(res.content.title, res.content.id))
elif res.error is not None:
print("[Batch get] Something went wrong: {}".format(res.error))
Delete items
You can use the Items().DeleteAll() method to batch delete a list of items from a specified vault using their unique identifiers. Deleted items remain available in Recently Deleted for 30 days.To delete the items you created in the previous step:// Delete multiple items from the same vault in a single batch
batchDeleteResponse, err := client.Items().DeleteAll(context.Background(), vaultID, itemIDs)
if err != nil {
panic(err)
}
for id, res := range batchDeleteResponse.IndividualResponses {
if res.Error != nil {
fmt.Printf("[Batch delete] Something went wrong: %s\\n", res.Error)
} else {
fmt.Printf("Deleted item %s\\n", id)
}
}
You can use the items.deleteAll() method to batch delete a list of items from a specified vault using their unique identifiers. Deleted items remain available in Recently Deleted for 30 days.To delete the items you created in the previous step:const batchDeleteResponse = await client.items.deleteAll(vaultId, itemIDs);
for (const [id, res] of Object.entries(
batchDeleteResponse.individualResponses,
)) {
if (res.error) {
console.log(
"[Batch delete] Something went wrong:",
res.error,
);
} else {
console.log("Deleted item", id);
}
}
You can use the items.delete_all() method to batch delete a list of items from a specified vault using their unique identifiers. Deleted items remain available in Recently Deleted for 30 days.vault_id = "your-vault-id"
item_ids = ["your-item-id-1", "your-item-id-2"]
# Delete multiple items from the same vault
batchDeleteResponse = await client.items.delete_all(vault_id, item_ids)
for id, res in batchDeleteResponse.individual_responses.items():
if res.error is not None:
print("[Batch delete] Something went wrong: {}".format(res.error))
else:
print("Deleted item {}".format(id))
Appendix: Field type constraints
Some supported field types have special requirements and constraints. Use these field definitions inside the fields list when creating or updating an item.
Address
For an Address type item field, the address field’s value is built using the address field’s details, because address string formats can differ according to the country. You must define which piece of the address each particular string corresponds to so that 1Password can properly create the address string.
To change the value of an Address field, edit the item field details directly, not the field value.
address := onepassword.NewItemFieldDetailsTypeVariantAddress(&onepassword.AddressFieldDetails{
Street: "123 Main St",
City: "Anytown",
State: "CA",
Zip: "12345",
Country: "USA",
})
addressField := onepassword.ItemField{
ID: "address",
Title: "Address",
SectionID: §ionID,
FieldType: onepassword.ItemFieldTypeAddress,
Value: "",
Details: &address,
}
{
id: "address",
title: "Address",
sectionId: "custom section",
fieldType: sdk.ItemFieldType.Address,
value: "",
details: {
type: "Address",
content: {
street: "1234 Elm St",
city: "Springfield",
country: "USA",
zip: "12345",
state: "IL",
},
},
},
from onepassword import (
AddressFieldDetails,
ItemField,
ItemFieldDetailsAddress,
ItemFieldType,
)
ItemField(
id="address",
title="Address",
sectionId="",
field_type=ItemFieldType.ADDRESS,
value="",
details=ItemFieldDetailsAddress(
content=AddressFieldDetails(
street="1234 Main St",
city="San Francisco",
state="CA",
zip="94111",
country="USA",
),
),
),
Date
For a Date type item field, the date field’s value must be a string formatted as YYYY-MM-DD. For example, 1998-03-15.
{
ID: "date",
Title: "Date",
SectionID: §ionID,
FieldType: onepassword.ItemFieldTypeDate,
Value: "1998-03-15",
},
{
id: "date",
title: "Date",
sectionId: "custom section",
fieldType: sdk.ItemFieldType.Date,
value: "1998-03-15",
},
from onepassword import ItemField, ItemFieldType
ItemField(
id="date",
title="Date",
section_id="",
field_type=ItemFieldType.DATE,
value="1998-03-15",
),
MonthYear
For a MonthYear type item field, the value must be a string formatted as MM/YYYY. For example, 10/2000.
{
ID: "month_year",
Title: "Month Year",
SectionID: §ionID,
FieldType: onepassword.ItemFieldTypeMonthYear,
Value: "03/1998",
},
{
id: "month_year",
title: "Month Year",
sectionId: "custom section",
fieldType: sdk.ItemFieldType.MonthYear,
value: "03/1998",
},
from onepassword import ItemField, ItemFieldType
ItemField(
id="month_year",
title="Month Year",
section_id="",
field_type=ItemFieldType.MONTHYEAR,
value="03/1998",
),
Reference
For a Reference type item field, the reference field’s value must be the unique identifier (ID) of another item that exists within the same vault. This ID should be a 26 character alphanumeric string. For example, vhn2qfnmizg6rw4iqottczq3fy.
{
ID: "reference",
Title: "Reference",
FieldType: onepassword.ItemFieldTypeReference,
SectionID: §ionID,
Value: "f43hnkatjllm5fsfsmgaqdhv7a",
},
{
id: "reference",
title: "Reference",
sectionId: "custom section",
fieldType: sdk.ItemFieldType.Reference,
value: "f43hnkatjllm5fsfsmgaqdhv7a",
},
from onepassword import ItemField, ItemFieldType
ItemField(
id="Reference",
title="Reference",
sectionId="",
field_type=ItemFieldType.REFERENCE,
value="f43hnkatjllm5fsfsmgaqdhv7a",
),
SSH Key
For an SSHKey type item field, the SSH key field’s value must be a valid SSH private key – a decrypted, PEM-encoded string. You can use private key strings generated from the source of your choice, or you can generate SSH keys in your SDK language using that language’s native support. Currently, if you attempt to pass an encrypted private key, you’ll see an error.
SSH key fields can only be added to items with the SSH Key category. You can add one SSH key field per item.
When you create an item with an SSH key field assigned to it, 1Password will generate a public key, fingerprint, and key type which are stored in the SSH key field details.
The following example shows how to generate a valid SSH private key in Go and adds it to a new SSH Key item in 1Password.// Generate the RSA key pair
privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
panic(err)
}
privBytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
panic(err)
}
// Encode the data into PEM format
sshKeyPEMBytes := string(pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: privBytes,
}))
vaultID := os.Getenv("OP_VAULT_ID")
sectionID := "extraDetails"
itemParams := onepassword.ItemCreateParams{
Title: "SSH Key Item Created With Go SDK",
Category: onepassword.ItemCategorySSHKey,
VaultID: vaultID,
Fields: []onepassword.ItemField{
{
ID: "private_key",
Title: "private key",
Value: sshKeyPEMBytes,
FieldType: onepassword.ItemFieldTypeSSHKey,
SectionID: §ionID,
},
},
Sections: []onepassword.ItemSection{
{
ID: sectionID,
Title: "Extra Details",
},
},
}
// Creates a new item based on the structure definition above
createdItem, err := client.Items().Create(context.Background(), itemParams)
if err != nil {
panic(err)
}
// Fetch all SSH key attributes
fmt.Println(createdItem.Fields[0].Value)
if sshAttributes := createdItem.Fields[0].Details.SSHKey(); sshAttributes != nil {
fmt.Println(createdItem.Fields[0].Details.SSHKey().PublicKey)
fmt.Println(createdItem.Fields[0].Details.SSHKey().Fingerprint)
fmt.Println(createdItem.Fields[0].Details.SSHKey().KeyType)
}
The following example shows how to generate a valid SSH private key in JavaScript and adds it to a new SSH Key item in 1Password.const privateKey = crypto.generateKeyPairSync("rsa", {
modulusLength: 4096, // 4096-bit key
privateKeyEncoding: {
type: "pkcs8", // PKCS#8 Private Key format
format: "pem",
},
});
// Create a SSH Key Item
let item = await client.items.create({
title: "SSH Key Item Created With JS SDK",
category: sdk.ItemCategory.SshKey,
vaultId: vaultId,
fields: [
{
id: "private_key",
title: "private key",
fieldType: sdk.ItemFieldType.SshKey,
value: privateKey.privateKey,
sectionId: "custom section",
},
],
sections: [
{
id: "custom section",
title: "my section",
},
],
});
console.log(item.fields[0].value);
console.log(item.fields[0].details.content.publicKey);
console.log(item.fields[0].details.content.fingerprint);
console.log(item.fields[0].details.content.keyType);
The following example shows how to generate a valid SSH private key in Python and adds it to a new SSH Key item in 1Password.from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from onepassword import (
ItemCategory,
ItemCreateParams,
ItemField,
ItemFieldType,
ItemSection,
)
# Generate a 4096-bit RSA private key
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=4096,
)
# Serialize the private key in PKCS8 format (PEM)
ssh_key_pkcs8_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
# Create an SSH Key item and add it to a vault
to_create = ItemCreateParams(
title="SSH Key Item Created With Python SDK",
category=ItemCategory.SSHKEY,
vault_id="your-vault-id",
fields=[
ItemField(
id="private_key",
title="private key",
field_type=ItemFieldType.SSHKEY,
value=ssh_key_pkcs8_pem,
sectionId="",
),
],
sections=[
ItemSection(id="", title=""),
],
)
created_item = await client.items.create(to_create)
print(created_item.fields[0].value)
print(created_item.fields[0].details.content.public_key)
print(created_item.fields[0].details.content.fingerprint)
print(created_item.fields[0].details.content.key_type)
TOTP
For a Totp type item field, the TOTP field’s value must either be a valid one-time password URL (for example, otpauth://totp/rsnjfceadiejs?secret=e4dw4xrdq34wd3qw3&issuer=vfsrfesfes), or a one-time password seed (for example, e4dw4xrdq34wd3qw3).
{
ID: "onetimepassword",
Title: "One-Time Password URL",
SectionID: §ionID,
FieldType: onepassword.ItemFieldTypeTOTP,
Value: "otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
},
{
id: "onetimepassword",
title: "One-Time Password URL",
sectionId: "custom section",
fieldType: sdk.ItemFieldType.Totp,
value:
"otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
},
from onepassword import ItemField, ItemFieldType
ItemField(
id="onetimepassword",
title="one-time-password",
section_id="",
field_type=ItemFieldType.TOTP,
value="otpauth://totp/my-example-otp?secret=jncrjgbdjnrncbjsr&issuer=1Password",
),
Troubleshooting
If you aren’t able to create, edit, or delete items and see an error that you “don’t have the right permissions to execute this argument,” check your service account’s permissions in the vault where the items are saved:
- Sign in to your account on 1Password.com.
- Select Developer in the sidebar.
- Choose the service account, then confirm that you see
Read & Write next to the vault in the Vaults table.
If your service account only has read access, you’ll need to create a new service account with read and write permissions.
Learn more