Package: pyonepassword
PYONEPASSWORDDescriptionA Python API to sign into and query a 1Password account using theopcommand.RequirementsPython >= 3.91Password command-line tool >= 2.0.0see1Password Developer DocumentationInternet connectivity to 1Password.comTheopcommand queries your online account, not your local vaultNote: This version ofpyonepassworddoes not support deprecatedop1.x versions. Support for those versions is still available, albeit with minimal maintanence. Seepyonepassword-legacyfor more information.Installationpython3-mpipinstallpyonepasswordOverviewpyonepasswordessentially has two parts:Convenience Python classes for the various objects that theopcommand returnsA full-fledged API for querying a 1Password accountIf you already have a workflow to drive theopcommand, handle authentication, and so forth, but would benefit from an API that can ingestop's JSON and give you Python objects, you're in luck, number one might be just what you need.On the other hand, if you're usingopmanually (maybe along sidejq), or in shell scripts (or maybe not at all), and you'd like a full-service Python API rather than console commands, number two does that.We'll get into some examples below for both of these.Example UsageObject APIpyonepasswordprovides Python classes for many of the objectsopreturns, including:Several "item" types (login, password, secure note, etc)UserUser List (e.g., from 'op user list')GroupGroup ListVaultVault ListAccountAccount ListAll of these classes provide assorted convenience properties. For exampleobj.created_atreturns a proper Pythondatetimeobject.All of the object types are fundamentally dictionaries, so their data can be accessed as such, and they can be serialized back to JSON.Also, all classes can be instantiated from either directly from a JSON string, or from an unserialized object.Take the following Login item as an example:{"id":"4smjvvepfbg3hencrmo7cozphe","title":"Example Login","version":2,"vault":{"id":"yhdg6ovhkjcfhn3u25cp2bnl6e"},"category":"LOGIN","last_edited_by":"RAXCWKNRRNGL7I3KSZOH5ERLHI","created_at":"2021-06-29T18:42:03Z","updated_at":"2022-03-17T03:40:49Z","sections":[{"id":"linked items","label":"Related Items"}],"fields":[{"id":"password","type":"CONCEALED","purpose":"PASSWORD","label":"password","value":"doth-parrot-hid-tussock-veldt","password_details":{"strength":"FANTASTIC"}},{"id":"username","type":"STRING","purpose":"USERNAME","label":"username","value":"zcutlip"},{"id":"notesPlain","type":"STRING","purpose":"NOTES","label":"notesPlain"}],"urls":[{"href":"http://example2.website"},{"primary":true,"href":"https://example.website"}]}In just a line of Python, you can create anOPLoginItemobject:frompyonepassword.api.object_typesimportOPLoginItemlogin_item=OPLoginItem(login_item_json)print(login_item.username)print(login_item.password)print(login_item.primary_url.href)# login_item is also a dictionary:print(login_item["username"]==login_item.username)Example usage of theOPclassIf you want to fully automate connecting to and querying a 1Password account, that's what theOPclass is for. It handles authentication (except for initial sign-in). And provides methods that are congruent to many of theopCLI tool's subcommands, such as:item_get()item_list()user_get()user_list()...... and so forth.All of these methods return objects types as described above. Also,item_get()returns the appropriate object type for the item, such asOPLoginItemorOPSecureNoteItem, as long aspyonepasswordhas a class for the returned item type.Note: In some cases theopcommand may return items that don't conform to the expected structure. When this happens, the item dictionary will fail to validate, an exception will be raised. There is API for relaxing item validation, globally, on a per-class basis, or a per-item basis. Seeitem-validation.mdfor more information.Sign-in and item retrievalBelow is an example demonstrating:Sign-inSpecifying a default vault for queriesRetrieving an item from 1Password by name or by UUIDOverriding the default vault to retrieve a subsequent item from 1PasswordimportgetpassfrompyonepasswordimportOPfrompyonepassword.api.exceptionsimport(OPSigninException,OPItemGetException,OPNotFoundException,OPConfigNotFoundException)# See examples/example-sign-in.py for more sign-in examplesdefdo_signin():# Let's check If biometric is enabled# If so, no need to provide a passwordifOP.uses_biometric():try:# no need to provide any authentication parameters if biometric is enabledop=OP()exceptOPAuthenticationException:print("Uh oh! Sign-in failed")exit(-1)else:# prompt user for a password (or get it some other way)my_password=getpass.getpass(prompt="1Password master password:\n")# You may optionally provide an account shorthand if you used a custom one during initial sign-in# shorthand = "arbitrary_account_shorthand"# return OP(account_shorthand=shorthand, password=my_password)# Or we'll try to look up account shorthand from your latest sign-in in op's config fileop=OP(password=my_password)returnopdefmain():op=do_signin()item_password=op.item_get_password("Example Login")# We can also look up the item by its UUID# as well as retrieve from an alternate vaultitem_password=op.item_get_password("ykhsbhhv2vf6hn2u4qwblfrmg4",vault="Private")Document retrievalBelow is an example demonstrating:Retrieving a document and its file name from 1Password, based on item nameRetrieving a document & file name from 1Password, based on UUIDop=do_signin()# File name and document title in 1Password are often different.# so we get back the file name, and the bytes object representing the documentfile_name,document_bytes=op.document_get("Example Login - 1Password Logo")# we can also look up the document by UUIDfile_name,document_bytes=op.document_get("bmxpvuthureo7e52uqmvqcr4dy")open(file_name,"wb").write(document_bytes)Signing out of 1PasswordBelow is an example demonstrating:Signing in, then signing out of 1PasswordSigning out and also forgetting a 1Password accountNote: Currentlypyonepassword's sign-out & forget support requires a signed-in session. It is not yet possible to forget an arbitrary account.defmain():op=do_signin()# do signoutop.signout()try:print(op.item_get_password("Example Login"))exceptOPItemGetException:# lookup fails since we signed outpass# now let's sign in again, then signout with forget=Trueop=do_signin()op.signout(forget=True)try:do_signin()exceptOPSigninException:# Sign-in fails since we erased the initial sign-in with forget=TruepassGetting Details for a Userop=OP(password=my_password)# User's name:user:OPUser=op.user_get("Firstname Lastname")# or the user's UUIDuser:OPUser=op.user_get(user_uuid)Getting Details for a Groupop=OP(password=my_password)# Group name:group:OPGroup=op.group_get("Team Members")# or the group's UUIDgroup:OPGroup=op.group_get("yhdg6ovhkjcfhn3u25cp2bnl6e")Getting Details for a Vaultop=OP(password=my_password)# Group name:vault:OPVault=op.vault_get("Test Data")# or the group's UUIDvault:OPVault=op.vault_get("yhdg6ovhkjcfhn3u25cp2bnl6e")Extending Item TypesIf any of the item types (login, password, etc.) are missing or don't provide sufficient properties or methods, it's very easy to add new ones or extend existing ones.Here's an example extendingOPLoginItem.frompyonepasswordimportOPfrompyonepassword.api.decoratorsimportop_register_item_typefrompyonepassword.api.object_typesimportOPLoginItem@op_register_item_typeclassOPEnhancedLoginItem(OPLoginItem):@propertydefcustom_property(self):returnself["custom_field"]op=OP()enhanced_login=op.item_get("Example Login",vault="Test Data")print(enhanced_login.custom_property)Item DeletionfrompyonepasswordimportOP# noqa: E402frompyonepassword.api.exceptionsimportOPItemDeleteException# noqa: E402defmain():op:OP()try:# op.item_delete() can take any identifier accepted by the 'op' command:# Usage:  op item delete [{ <itemName> | <itemID> | <shareLink> | - }] [flags]deleted_uuid=op.item_delete("Example Login")# noqa: F841# if desired inspect resulting UUID to ensure it's what was# ExpectedexceptOPItemDeleteExceptionasope:# 'op' command can fail for a few reaons, including# - item not found# - duplicate item names# Inspect the error message from the commandprint(ope.err_output)Item CreationFor details on creating new items in a 1Password vault, seeitem-creation.mdAlso see the examles inexamples/item_creationItem EditingFor details on editing existing items in a 1Password vault, seeitem-editing.mdAlso see the examles inexamples/item_editingDocument EditingFor details on editing existing document item file contents, seedocument-editing.mdSee examples inexamples/document_editingUser EditingUser editing is supported via theOP.user_edit()method. It supports toggling travel mode on and off, as well as setting a new user name. Only one user at a time may be edited via this method.See examples inexamples/user_editingMore ExamplesLots more examples are available in theexamplesdirectory