Package: harborapi
harborapiPython async client for the Harbor REST API v2.0 based on the official Harbor REST API specification.NOTE:The official Harbor API spec is hand-written, and numerous errors and inconsistencies have been found in it. This library attempts to work around these issues as much as possible, but errors may still occur. If you find any errors, please open an issue.FeaturesAsync APIExtensive type hint coverageData validationwithPydanticBuilt-inretry functionalitywithbackoffOptionalRichsupportInstallationpipinstallharborapiDocumentationDocumentation is availablehere. The documentation is still a work in progress, and you may have to dig around a bit to find what you're looking for.Creating proper documentation for the Pydantic models is priority number one right now, but is largely blocked by the lack of inheritance support in themkdocstrings python plugin.Quick StartAuthenticationfromharborapiimportHarborAsyncClientclient=HarborAsyncClient(url="https://demo.goharbor.io/api/v2.0/",username="username",secret="secret",# ORbasicauth="base64-basic-auth-credentials",# ORcredentials_file="/path/to/robot-credentials-file.json",)Get all projectsimportasynciofromharborapiimportHarborAsyncClientclient=HarborAsyncClient(# ...)asyncdefmain()->None:# Get all projectsprojects=awaitclient.get_projects()forprojectinprojects:print(project.name)# If you have rich installed:importrichforprojectinprojects:rich.print(project)asyncio.run(main())Create a projectimportasynciofromharborapiimportHarborAsyncClientfromharborapi.modelsimportProjectReq,ProjectMetadataclient=HarborAsyncClient(# ...)asyncdefmain()->None:project_path=awaitclient.create_project(ProjectReq(project_name="test-project",metadata=ProjectMetadata(public=True,),))print(f"Project created:{project_path}")asyncio.run(main())All endpoints are documented in theendpoints documentation.Disclaimerharborapimakes use of code generation for its data models, but it doesn't entirely rely on it like, for example,githubkit. Thus, while the library is based on the Harbor REST API specification, it is not beholden to it. The official schema contains several inconsistencies and errors, and this package takes steps to rectify some of these locally until they are fixed in the official Harbor API spec.harborapiattempts to improve endpoint descriptions where possible and fix models with fields given the wrong type or wrongly marked as required. Without these changes, the validation provided by the library would be unusable for certain endpoints, as these endpoints can, in certain cases, return data that is inconsistent with the official API specification, thus breaking the model validation.To return the raw API responses without validation and type conversion, setraw=Truewhen instantiating the client. For more information, check thedocumentationon validation.Implemented endpointsArtifactAuditlogConfigureGarbage CollectionHealthIconImmutableLabelLdapOIDCPingPreheatProjectProject MetadataPurgeQuotaRegistryReplicationRepositoryRetentionRobotRobotv1ScanScan Data ExportScanallScannerSearchStatisticSystem CVE AllowlistSystem InfoUserUsergroupWebhooks0.23.1- 2024-01-22ChangedAll URLs now point to new repo owner.0.23.0- 2023-12-19The big Pydantic V2 update. This is a major update in terms of both scope and API compatibility.ChangedModel validation has become more strict.Most importantly,strfields will no longer coerceintvalues to strings.SeePydantic docsfor more information.Models without fields now inherit frompydantic.RootModeland have a single field calledroot. These models have a special__getitem__method, so they can be accessed like a dict. Currently, these are:harborapi.models.ExtraAttrsharborapi.models.Annotationsharborapi.models.ResourceListharborapi.models.QuotaRefObjectharborapi.models.EventTypeharborapi.models.NotifyTypeharborapi.models.PayloadFormatTypeharborapi.models.AdditionLinksharborapi.models.InternalConfigurationsResponseharborapi.models.ScanOverviewharborapi.models.AdditionLinksharborapi.models.ProjectMetadata:retention_idnow accepts both string and integer arguments. Band-aid fix until Harbor fixes their API spec and specifies that all retention IDs should be ints, not strings.harborapi.models.Artifact:scan_overviewis now a mapping of MIME types and their associated scan overview. Previously, we used some dirty metaprogramming to populate this field with the first scan overview found in the mapping. A newscanattribute has been added to access the first scan overview in the mapping, which is the same as the old behavior. This ensures serializing the model matches the original JSON from the API.harborapi.ext.report.ArtifactReport:No longer supports iteration directly on the object itself. Use theartifactsattribute instead.Bool to string converter now limited toharborapi.models.ProjectMetadatamodel. This aberrant behavior is limited to ProjectMetadata, so the converter has been moved to the model itself. This band-aid fix will remain until Harbor changes their API spec and make these fields bools.Removedmissing_okparameter for all relevant client methods.Deprecatedharborapi.models._modelsmodule. All main API spec models are now definedharborapi.models.models.harborapi.models._scannermodule. All scanner models are now defined inharborapi.models.scanner.0.22.3- 2023-09-13ChangedLower bounds of dependencies loosened to allow for certain older versions:httpx>= 0.22.0typing_extensions>= 4.40.22.2- 2023-09-13ChangedLicense changed from GPLv3 to MIT.0.22.1- 2023-09-05ChangedReduced sdist size significantly by removing unnecessary files (docs, tests, etc.).0.22.0- 2023-08-01ChangedPydantic version capped at <2.0.0.Migration to Pydantic V2 will begin soon.0.21.0- 2023-06-08AddedMissing optionallimitargument for methods that fetch multiple resources:HarborAsyncClient.get_replication_tasksHarborAsyncClient.search_usergroupsHarborAsyncClient.get_webhook_policy_last_triggerHarborAsyncClient.search_ldap_groupsHarborAsyncClient.search_ldap_usersHarborAsyncClient.get_registry_adaptersHarborAsyncClient.get_artifact_build_historyChangedHarborAsyncClient.get_replication_tasksargument order changed. Nowstatusandresource_typefollow the required argumentproject_idinstead of after the optionalquery,sort,page,page_sizeandlimitarguments.harborapi.models.ScannerPropertiesnow takes an arbitrary number of extra fields instead of using a__root__field.RemovedDeprecated fields removed in API spec(bf7c82b):harborapi.models.Tag.signedharborapi.models.GeneralInfo.with_notary0.20.0- 2023-05-30ChangedHarborAsyncClient.delete_scannernow raisesHarborAPIExceptionif no scanner response is returned from the API (wasUnprocessableEntitybefore).RemovedLoguru dependency. The library now uses the standard Python logging library for logging purposes. SeeLoggingin the docs for more information.0.19.0- 2023-05-15AddedBaseModel.get_model_fields, a class method which returns a list of names of all fields defined in the model's schema.ChangedBREAKING:Updated model schemas (`10c54c0..b232c90). Changes listed below:Add model:PayloadFormatTypeAdd model:PayloadFormatAdd field:SupportedWebhookEventTypes.payload_formatsAdd field:Accessory.subject_artifact_digestAdd field:Accessory.subject_artifact_repoUpdate field:Access.resourcedescriptionUpdate field:Access.actiondescriptionUpdate field:ComponentHealthStatus.statusdescriptionUpdate field:Robot.namedescriptionUpdate field:Robot.expires_atdescriptionUpdate field:RobotCreate.namedescriptionDeprecate field:Accessory.subject_artifact_idRemove model:ChartMetadata(deprecated)Remove model:ChartVersion(deprecated)Remove model:SearchResult(deprecated)Remove fieldProject.chart_count(deprecated)0.18.1- 2023-05-12AddedBaseModel.convert_to, which allows converting a model to another model type that has a similar schema, such asProjecttoProjectReq.FixedBool to string converter onBaseModelnow correctly handles assignments.0.18.0- 2023-05-05AddedNew context manager for temporarily disabling retrying:HarborAsyncClient.no_retryNew context manager for temporarily disabling validation:HarborAsyncClient.no_validationNew context manager for temporarily enabling raw mode:HarborAsyncClient.raw_modeAcceptpasswordkwarg forHarborAsyncClientconstructor, while emitting warning for it. It isn't encouraged (or documented) to usepassword, but it might be more natural for many users thansecret, so we allow it, since we already accept arbitrary kwargs.ChangedRetrySettings.max_triesnow only accepts values greater than 0.RetrySettings.max_timenow only accepts values greater or equal to 0.Models fields assignments are now validated by default.models.base.BaseModel.bool_converterrenamed tomodels.base.BaseModel._bool_converterto hide it in IDE autocompletion. This shouldn't be a breaking change for anyone, since it was never documented or intended to be used by anyone outside of the library.0.17.0- 2023-05-03AddedConfigurable retrying of failed requests using the newRetrySettingsclass, which can be passed to theHarborAsyncClientconstructor with theretrykeyword argument. See theretry docsfor more information.FixedMethods that fetched files using the wrongAcceptheader have been fixed. This includes:HarborAsyncClient.download_scan_exportHarborAsyncClient.get_system_certificateChangedharborapi.errors.StatusError.status_codeis now always an integer. Returns 0 if no request is associated with the error.0.16.2- 2023-04-26AddedDisclaimer forharborapi.HarborAsyncClient.delete_retention_policy, warning that it can break a project due to a bug in Harbor.ChangedMoveharborapi.client.ResponseLogandharborapi.client.ResponseLogEntrytoharborapi.responselogmodule.Fixedharborapi.models.VulnerabilityItem.severityfield has had its type reverted toSeverityfromOptional[Severity], which was a regression introduced in v0.16.0.harborapi.ext.regex.matchreturn type annotation is now correctly marked asOptional[Match[str]]instead ofMatch[str].harborapi.HarborAsyncClient.get_retention_tasksmissinglimitparameter in docstring.0.16.1- 2023-04-24FixedPassing aNativeReportSummarytoArtifact.scan_overviewno longer raises aValidationErrorexception.0.16.0- 2023-04-24ChangedBroken or incomplete models are now completely redefined inharborapi.models.modelsto provide better documentation both in the code and in the generated documentation. This change should be backwards-compatible.harborapi.HarborAsyncClient.add_group_membernow has a clearner warning describing its purpose and the alternative methods to use instead.0.15.3- 2023-04-20FixedModels with fields that wrongly required dicts of dicts now accept dicts of any for the affected fields:harborapi.models.RetentionRule.paramsharborapi.models.ImutableRule.paramsUntil the official API spec is fixed, this is the best we can do.0.15.2- 2023-04-18Removedharborbeing added as an executable script installed by the project. This was a mistake, as theharborexecutable script is intended to be exposed byharbor-cli.0.15.1- 2023-04-17AddedHarborAsyncClient.authenticate(). This method can be used to re-authenticate the client with new credentials without having to create a new client instance.ChangedHarborAsyncClient.get_artifact_vulnerabilities()now always returns aharborapi.models.HarborVulnerabilityReportobject. If the artifact has no vulnerabilities or the report cannot be processed, an exception is raised.Removedconfigargument fromHarborAsyncClient.__init__(). Theconfigargument was never implemented.0.15.0- 2023-04-13AddedRetention methods:HarborAsyncClient.get_project_retention_id()HarborAsyncClient.get_retention_policy()HarborAsyncClient.create_retention_policy()HarborAsyncClient.update_retention_policy()HarborAsyncClient.delete_retention_policy()HarborAsyncClient.get_retention_tasks()HarborAsyncClient.get_retention_metadata()HarborAsyncClient.get_retention_execution_task_log()HarborAsyncClient.get_retention_executions()HarborAsyncClient.start_retention_execution()HarborAsyncClient.stop_retention_execution()0.14.1- 2023-04-11Addedverifykwarg forHarborAsyncClientandHarborClientwhich is passed to the underlyinghttpx.AsyncClient. This is useful for self-signed certificates, or if you want to control the SSL verification yourself. Seehttpx documentationfor more information.harborapi.exceptions.StatusError.responsewhich holds the HTTPX response object that caused the exception.FixedPotential circular import error inharborapi.ext, whereHarborAsyncClientis imported as a type annotation.0.14.0- 2023-04-05Changedlimitkwarg now treats0as no limit. Previously,0meant no results would be returned.BREAKING:harborapi.ext.artifact.ArtifactInfo.tagsnow returns a list of tags instead of a comma-separated string of tags. This gives more flexibility to work with the various tags, and is more consistent with the rest of the library. If you need the comma-separated string, you can use", ".join(artifact_info.tags).0.13.1- 2023-04-03FixedPagination URLs containing spaces are now properly handled. This could occur if passing a a query parameter with a list of items, such as?q=operation={push pull}or?q=operation=(push pull).0.13.0- 2023-03-31ChangedHarborAsyncClient.update_project_member_role()now accepts integer arguments for itsrole_idparameter, sinceRoleRequestonly has a single field (role_id).FixedPotential bug withmodels.VulnerabilitySummaryifsummaryisNone.JSON parsing exception inHarborAsyncClient.get_audit_log_rotation_schedule()that could occur if no schedule exists. The API returns an emtpy200 OKresponse, which is now handled correctly (emptyExecHistoryobject).Missing docstring forHarborAsycClient.get_project_members.0.12.0- 2023-03-14ChangedBREAKING:HarborAsyncClient.export_scan_data()now takes the arguments in the order (criteria,scan_type). Furthermore,scan_typenow has a default argument of"application/vnd.security.vulnerability.report; version=1.1", per theblog postdescribing this new feature. It should not be necessary specify this argument, but it is still possible to do so if you need to.0.11.2- 2023-03-14FixedActually addsgroup_nameparameter forHarborAsyncClient.get_usergroups()this time.AddedMissinggroup_nameandlimitparameters forHarborAsyncClient.get_usergroups().0.11.1- 2023-03-14AddedMissinggroup_nameandlimitparameters forHarborAsyncClient.get_usergroups().0.11.0- 2023-03-10AddedHarborAsyncClient.get_system_certificate()Returns the system certificate. (GET /api/v2.0/systeminfo/getcert)ChangedBREAKING: Methods that download files, now returnFileResponseinstead of a bytes object.FileResponsecontains the file contents along with its metadata. The object can be passed tobytes()to get the response contents, otherwise it can be accessed via theFileResponse.contentattribute.BREAKING: Renamed "purge" methods to better reflect their purpose of audit log rotation:HarborAsyncClient.get_purge_audit_log_status()->HarborAsyncClient.get_audit_log_rotation()HarborAsyncClient.get_purge_audit_log()->HarborAsyncClient.get_audit_log_rotation_log()HarborAsyncClient.stop_purge_audit_log()->HarborAsyncClient.stop_audit_log_rotation()HarborAsyncClient.get_purge_audit_log_schedule()->HarborAsyncClient.get_audit_log_rotation_schedule()HarborAsyncClient.create_purge_audit_log_schedule()->HarborAsyncClient.create_audit_log_rotation_schedule()HarborAsyncClient.update_purge_audit_log_schedule()->HarborAsyncClient.update_audit_log_rotation_schedule()HarborAsyncClient.get_purge_audit_logs()->HarborAsyncClient.get_audit_log_rotation_history()0.10.0- 2023-02-28Addedharborapi.ext.artifact.ArtifactInfo.name_with_digest_fullwhich returns the artifact name with the full SHA256 digest, not just the first 15 characters likename_with_digest.Audit log purging methods.HarborAsyncClient.get_purge_audit_log_status()HarborAsyncClient.get_purge_audit_log()HarborAsyncClient.stop_purge_audit_log()HarborAsyncClient.get_purge_audit_log_schedule()HarborAsyncClient.create_purge_audit_log_schedule()HarborAsyncClient.update_purge_audit_log_schedule()HarborAsyncClient.get_purge_audit_logs()Documentation forHarborAsyncClient.get_project_deletable().Webhook methods.HarborAsyncClient.get_webhook_jobs()HarborAsyncClient.get_webhook_policies()HarborAsyncClient.get_webhook_policy()HarborAsyncClient.create_webhook_policy()HarborAsyncClient.update_webhook_policy()HarborAsyncClient.delete_webhook_policy()HarborAsyncClient.get_webhook_policy_last_trigger()HarborAsyncClient.get_webhook_supported_events()Scan Data Export MethodsHarborAsyncClient.get_scan_export()HarborAsyncClient.get_scan_exports()HarborAsyncClient.export_scan_data()HarborAsyncClient.download_scan_export()Icon methodsHarborAsyncClient.get_icon()Label methodsHarborAsyncClient.get_label()HarborAsyncClient.create_label()HarborAsyncClient.delete_label()HarborAsyncClient.get_labels()Project member methodsHarborAsyncClient.get_project_member()HarborAsyncClient.add_project_member()HarborAsyncClient.add_project_member_user()HarborAsyncClient.add_project_member_group()HarborAsyncClient.update_project_member_role()HarborAsyncClient.remove_project_member()HarborAsyncClient.get_project_members()New methods for controlling the size of the response log.harborapi.client.ResponseLog.resize()harborapi.client.ResponseLog.clear()Documentedherebasicauthas a parameter forHarborAsyncClient.__init__()to pass in base64 basic auth credentials.Changedmissing_okparameter for DELETE methods has been deprecated. Manually  handleharborapi.exceptions.NotFoundinstead. This parameter will stop working in version 1.0.0, and be removed altogether in a later release.harborapi.models.Repository.split_name()now returns a tuple instead of a list, as its docstring states it should.DEPRECATED: Usingcredentialsas a parameter forHarborAsyncClient.__init__is deprecated. Usebasicauthinstead.HarborAsyncClient.credentialsis now a Pydantic SecretStr, which prevents it from being printed in clear text when locals are dumped, such as when printing the client object. To access the value, useHarborAsyncClient.credentials.get_secret_value().RemovedExplicit logging calls fromHarborAsyncClient.set_user_cli_secret()andHarborAsyncClient.set_user_password(). The exception handler handles logging if configured.0.9.0- 2023-02-21ChangedUpdatedharborapi.modelsto match the latest version of the Harbor API specgoharbor/harbor@d03f0dc.harborapi.models.GeneralInfo.with_chartmuseumhas been removed from the API spec, but remains on the model for backwards compatibility. In the future, this field will be removed, as the API will never return this it in sufficiently new versions of Harbor.0.8.6- 2023-02-20FixedModels withharborapi.models.ScheduleObjfields are now correctly validated when the Harbor API responds with a value of"Schedule"for the fieldScheduleObj.type, which is not a valid value for the enum according to their own spec.0.8.5- 2023-02-20AddedNativeReportSummary.severity_enumwhich returns the severity of the report as aharborarpi.scanner.Severityenum, which can be used for comparisons between reports.Fixedharborarpi.scanner.Severityenum not having aNonevalue, which is observed when a report has no vulnerabilities.0.8.4- 2023-02-14FixedCertain resource enumeration methods missing thelimitparameter.HarborAsyncClient.get_gc_jobs()ignoring user parameters.0.8.3- 2023-02-14ChangedBREAKING:HarborAsyncClient.update_robot_tokenrenamed toHarborAsyncClient.refresh_robot_tokento better reflect the API endpoint name and purpose.FixedPagination failing when one or more query parameter values included a comma.CertainHarborAsyncClientmethods having missing or incomplete docstrings.0.8.2- 2023-02-09FixedHarborAsyncClient.get_registry_providersnow returns aRegistryProvidersobject, which is a model whose only attributeprovidersis a dict ofRegistryProviderInfoobjects. Previously this method attempted to return a list ofRegistryProviderInfoobjects, but this was incorrect.0.8.1- 2023-02-09ChangedBackoff handlers for HTTP methods now handle a more strict subset ofhttpx.RequestErrorexceptions. This is to avoid retrying on exceptions that will never succeed such ashttpx.UnsupportedProtocol.0.8.0- 2023-02-08Addedlimitparameter for all methods that return a list of items. This parameter is used to limit the number of items returned by the API. See thedocsfor more details.Removedretrieve_allparameter for all methods that return a list of items. Use the newlimitparameter to control the number of results to retrieve. Passingretrieve_allto these methods will be silently ignored. In the future this will raise a DeprecationWarning.0.7.1- 2023-02-07AddedNew parametersrawandvalidatetoHarborAsyncClientandHarborClientto control whether the client returns the raw data from the API, and whether the client validates the data from the API, respectively. See thedocsfor more details.0.7.0- 2023-02-06AddedNew models from2022-11-28 spec update.ChangedUpdated models from2022-11-28 spec update.Generated models are now defined inmodels._modelsandmodels._scanner, and the overrides for these models are defined inmodels.modelsandmodels.scannerrespectively. This is to make it easier to regenerate the models in the future while keeping the extended functionality (such asRepository.project_name,ScanOverview.__new__, etc.) for these classes intact, since that is now declared separately from the generated models. Furthermore,models.modelsandmodels.scannerboth re-export all the generated models so that the API remains unchanged. See the Justfile for more details on how the models are generated.FixedHarborAsyncClient.search()raising an error when finding Helm Charts with an emptyenginefield.RemovedBREAKING:HarborAsyncClient.get_internal_config(). This endpoint is meant for internal usage only, and the new model definitions don't seem to play well with it. If you need this endpoint, please open an issue.0.6.0- 2023-01-30ChangedBREAKING: Themax_depthparameter of theas_table()andas_panel()methods on all models now starts counting from 1 instead of 0.max_depth=0now means "no limit", andmax_depth=1means "only show the top level" (previouslymax_depth=0meant "only show the top level" andmax_depth=1meant "show the top level and one level below")0.5.0- 2023-01-17AddedChangelogRich as optional dependency:pip install harborapi[rich]ChangedUse Hatch as build system.