diff --git a/Makefile b/Makefile index 6fc3467d..2ddd4d11 100644 --- a/Makefile +++ b/Makefile @@ -41,12 +41,43 @@ sync-minio-version: @sed -i "s|DEBURL|${DEB}|g" source/conf.py @sed -i "s|RPMURL|${RPM}|g" source/conf.py +sync-java-docs: + @echo "Retrieving Java docs from github.com/minio/minio-java" + @$(eval LATEST = $(shell wget -q https://api.github.com/repos/minio/minio-java/releases/latest -O - | jq -r '.tag_name')) + @echo "Latest stable is ${LATEST}" + $(shell wget -q -O source/sdk/java/API.md https://raw.githubusercontent.com/minio/minio-java/${LATEST}/docs/API.md) + +sync-python-docs: + @echo "Retrieving Python docs from github.com/minio/minio-py" + @$(eval LATEST = $(shell wget -q https://api.github.com/repos/minio/minio-py/releases/latest -O - | jq -r '.tag_name')) + @echo "Latest stable is ${LATEST}" + $(shell wget -q -O source/sdk/python/API.md https://raw.githubusercontent.com/minio/minio-py/${LATEST}/docs/API.md) + +sync-go-docs: + @echo "Retrieving Python docs from github.com/minio/minio-py" + @$(eval LATEST = $(shell wget -q https://api.github.com/repos/minio/minio-go/releases/latest -O - | jq -r '.tag_name')) + @echo "Latest stable is ${LATEST}" + $(shell wget -q -O source/sdk/go/API.md https://raw.githubusercontent.com/minio/minio-go/${LATEST}/docs/API.md) + +sync-dotnet-docs: + @echo "Retrieving Python docs from github.com/minio/minio-py" + @$(eval LATEST = $(shell wget -q https://api.github.com/repos/minio/minio-dotnet/releases/latest -O - | jq -r '.tag_name')) + @echo "Latest stable is ${LATEST}" + $(shell wget -q -O source/sdk/dotnet/API.md https://raw.githubusercontent.com/minio/minio-dotnet/${LATEST}/Docs/API.md) + +sync-deps: + @echo "Synchronizing all external dependencies" + @make sync-minio-version + @make sync-java-docs + @make sync-python-docs + @make sync-go-docs + @make sync-dotnet-docs + stage: @make clean && make html python -m http.server --directory $(BUILDDIR)/$(GITDIR)/html publish: - @make sync-minio-version @make clean make html diff --git a/requirements.txt b/requirements.txt index 9a32e513..aefbae8b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ +docutils == 0.17 sphinx == 3.5.0 sphinx-copybutton == 0.4.0 sphinx-design == 0.0.12 @@ -5,4 +6,4 @@ sphinx-markdown-tables == 0.0.15 Sphinx-Substitution-Extensions == 2020.9.30.0 sphinx-togglebutton === 0.2.3 sphinxcontrib-images === 0.9.4 -myst-parser === 0.15.1 \ No newline at end of file +myst-parser === 0.16.1 \ No newline at end of file diff --git a/source/concepts/feature-overview.rst b/source/concepts/feature-overview.rst deleted file mode 100644 index cf15f566..00000000 --- a/source/concepts/feature-overview.rst +++ /dev/null @@ -1,47 +0,0 @@ -===================== -MinIO Server Features -===================== - -MinIO’s enterprise class features represent the standard in the object storage -space. From the AWS S3 API to S3 Select and our implementations of inline -erasure coding and security, our code is widely admired and frequently copied by -some of the biggest names in technology and business. - -The following table lists MinIO features and their corresponding documentation: - -.. list-table:: - :header-rows: 1 - :widths: 30 70 - - * - Feature - - Description - - * - :doc:`Bucket Notifications ` - - MinIO Bucket Notifications allows you to automatically publish - notifications to one or more configured notification targets when - specific events occur in a bucket. - - * - :doc:`Bucket Versioning ` - - MinIO Bucket Versioning supports keeping multiple "versions" of an - object in a single bucket. Write operations which would normally - overwrite an existing object instead result in the creation of a new - versioned object. - - * - :doc:`Erasure Coding ` - - MinIO Erasure Coding is a data redundancy and availability feature that - allows MinIO deployments to automatically reconstruct objects on-the-fly - despite the loss of multiple drives or nodes on the cluster. Erasure - coding provides object-level healing with less overhead than adjacent - technologies such as RAID or replication. - - * - :ref:`Server-Side Bucket Replication ` - - MinIO Server-Side Bucket Replication is an automatic bucket-level - configuration that synchronizes objects between MinIO clusters. - MinIO supports one-way "active-passive" and two-way "active-active" - configurations. - -.. toctree:: - :titlesonly: - :hidden: - - /concepts/erasure-coding diff --git a/source/index.rst b/source/index.rst index be6431ff..5f9c6cce 100644 --- a/source/index.rst +++ b/source/index.rst @@ -108,7 +108,7 @@ such as versioning and replication. For early development and application, applications can authenticate using the :guilabel:`RootUser` and :guilabel:`RootPass` credentials. For long-term development and production, create dedicated users. - See :doc:`/security/security-overview` for more information. + See :doc:`/security/iam-overview` for more information. You can also use the :mc:`mc` commandline tool to perform operations on the MinIO server. Use :mc:`mc alias set` to update the ``myminio`` alias with @@ -157,15 +157,16 @@ without validating their usage do so at their own risk. :hidden: /introduction/minio-overview - /concepts/feature-overview - Object Retention /installation/deployment-and-management + /security/iam-overview + /security/encryption-overview + Object Retention /lifecycle-management/lifecycle-management-overview /replication/replication-overview - /security/security-overview /monitoring/monitoring-overview /reference/minio-mc /reference/minio-mc-admin /reference/minio-server/minio-server /reference/minio-server/minio-gateway /console/minio-console + /sdk/minio-drivers \ No newline at end of file diff --git a/source/installation/deploy-minio-distributed.rst b/source/installation/deploy-minio-distributed.rst index 5ad48f61..9032fbc8 100644 --- a/source/installation/deploy-minio-distributed.rst +++ b/source/installation/deploy-minio-distributed.rst @@ -46,12 +46,12 @@ Prerequisites Networking and Firewalls ~~~~~~~~~~~~~~~~~~~~~~~~ -Each node should have full bidirectional network access to every other -node in the deployment. For containerized or orchestrated infrastructures, -this may require specific configuration of networking and routing -components such as ingress or load balancers. Certain operating systems -may also require setting firewall rules. For example, the following command -explicitly opens the default MinIO server API port ``9000`` for servers running firewalld : +Each node should have full bidirectional network access to every other node in +the deployment. For containerized or orchestrated infrastructures, this may +require specific configuration of networking and routing components such as +ingress or load balancers. Certain operating systems may also require setting +firewall rules. For example, the following command explicitly opens the default +MinIO server API port ``9000`` for servers running firewalld : .. code-block:: shell :class: copyable @@ -59,6 +59,8 @@ explicitly opens the default MinIO server API port ``9000`` for servers running firewall-cmd --permanent --zone=public --add-port=9000/tcp firewall-cmd --reload +All MinIO servers in the deployment *must* use the same listen port. + If you set a static :ref:`MinIO Console ` port (e.g. ``:9001``) you must *also* grant access to that port to ensure connectivity from external clients. @@ -242,7 +244,7 @@ MinIO *and* the ``minio.service`` file. The following examples assumes that: - The deployment has a single server pool consisting of four MinIO server hosts - with sequential hostnames: + with sequential hostnames. .. code-block:: shell @@ -270,8 +272,10 @@ Modify the example to reflect your deployment topology: # # The following example covers four MinIO hosts # with 4 drives each at the specified hostname and drive locations. + # The command includes the port that each MinIO server listens on + # (default 9000) - MINIO_VOLUMES="https://minio{1...4}.example.net/mnt/disk{1...4}/minio" + MINIO_VOLUMES="https://minio{1...4}.example.net:9000/mnt/disk{1...4}/minio" # Set all MinIO server options # @@ -300,7 +304,7 @@ Modify the example to reflect your deployment topology: # This value *must* match across all MinIO servers. If you do # not have a load balancer, set this value to to any *one* of the # MinIO hosts in the deployment as a temporary measure. - MINIO_SERVER_URL="https://minio.example.net" + MINIO_SERVER_URL="https://minio.example.net:9000" You may specify other :ref:`environment variables ` or server commandline options as required diff --git a/source/installation/expand-minio-distributed.rst b/source/installation/expand-minio-distributed.rst index 533807a3..9fd75069 100644 --- a/source/installation/expand-minio-distributed.rst +++ b/source/installation/expand-minio-distributed.rst @@ -53,6 +53,8 @@ MinIO server API port ``9000`` on servers using ``firewalld``: firewall-cmd --permanent --zone=public --add-port=9000/tcp firewall-cmd --reload +All MinIO servers in the deployment *must* use the same listen port. + If you set a static :ref:`MinIO Console ` port (e.g. ``:9001``) you must *also* grant access to that port to ensure connectivity from external clients. @@ -311,8 +313,11 @@ Modify the example to reflect your deployment topology: # The second set of hostnames and volumes is the newly added pool. # The pool has sufficient stripe size to meet the existing erasure code # parity of the deployment (2 x EC:4) + # + # The command includes the port on which the MinIO servers listen for each + # server pool. - MINIO_VOLUMES="https://minio{1...4}.example.net/mnt/disk{1...4}/minio https://minio{5...12}.example.net/mnt/disk{1...8}/minio" + MINIO_VOLUMES="https://minio{1...4}.example.net:9000/mnt/disk{1...4}/minio https://minio{5...12}.example.net:9000/mnt/disk{1...8}/minio" # Set all MinIO server options # @@ -341,7 +346,7 @@ Modify the example to reflect your deployment topology: # This value *must* match across all MinIO servers. If you do # not have a load balancer, set this value to to any *one* of the # MinIO hosts in the deployment as a temporary measure. - MINIO_SERVER_URL="https://minio.example.net" + MINIO_SERVER_URL="https://minio.example.net:9000" You may specify other :ref:`environment variables ` or server commandline options as required diff --git a/source/introduction/minio-overview.rst b/source/introduction/minio-overview.rst index 65e9798c..eafab7d0 100644 --- a/source/introduction/minio-overview.rst +++ b/source/introduction/minio-overview.rst @@ -74,8 +74,10 @@ Deployment Architecture :ref:`Server Pool ` A set of MinIO :mc-cmd:`minio server` nodes which pool their drives and - resources for supporting object storage/retrieval requests. The - :mc-cmd:`~minio server HOSTNAME` argument passed to the + resources for supporting object storage/retrieval requests. Server pools + support horizontal expansion for MinIO deployments. + + The :mc-cmd:`~minio server HOSTNAME` argument passed to the :mc-cmd:`minio server` command represents a Server Pool: .. code-block:: shell @@ -127,11 +129,20 @@ Deployment Architecture Deploying MinIO --------------- -Users deploying onto a Kubernetes cluster should start with our -:docs-k8s:`Kubernetes documentation <>`. +.. list-table:: + :stub-columns: 1 + :widths: 40 60 + :width: 100% -For bare-metal environments, including private cloud services -or containerized environments, install and run the :mc:`minio server` on -each host in the MinIO deployment. -See :ref:`minio-installation` for more information. + * - Baremetal + - :ref:`deploy-minio-distributed` + :ref:`expand-minio-distributed` + * - Kubernetes + - :docs-k8s:`MinIO Kubernetes Operator <>` + +.. toctree:: + :titlesonly: + :hidden: + + /concepts/erasure-coding diff --git a/source/concepts/bucket-versioning.rst b/source/object-retention/bucket-versioning.rst similarity index 100% rename from source/concepts/bucket-versioning.rst rename to source/object-retention/bucket-versioning.rst diff --git a/source/object-retention/minio-object-retention.rst b/source/object-retention/minio-object-retention.rst index 75bba5af..5bfdd7e5 100644 --- a/source/object-retention/minio-object-retention.rst +++ b/source/object-retention/minio-object-retention.rst @@ -56,5 +56,5 @@ Both versioning and object locking features are available only with :titlesonly: :hidden: - Object Versioning + Object Versioning Object Locking \ No newline at end of file diff --git a/source/sdk/dotnet/API.md b/source/sdk/dotnet/API.md new file mode 100644 index 00000000..e9b131ed --- /dev/null +++ b/source/sdk/dotnet/API.md @@ -0,0 +1,1437 @@ +# .NET Client API Reference [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +## Initialize MinIO Client object. + +## MinIO + +```cs +var minioClient = new MinioClient("play.min.io", + "Q3AM3UQ867SPQQA43P2F", + "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG" + ).WithSSL(); +``` + +## AWS S3 + + +```cs +var s3Client = new MinioClient("s3.amazonaws.com", + "YOUR-ACCESSKEYID", + "YOUR-SECRETACCESSKEY" + ).WithSSL(); +``` + +| Bucket operations | Object operations | Presigned operations | Bucket Policy Operations +|:--- |:--- |:--- |:--- | +| [`makeBucket`](#makeBucket) |[`getObject`](#getObject) |[`presignedGetObject`](#presignedGetObject) | [`getBucketPolicy`](#getBucketPolicy) | +| [`listBuckets`](#listBuckets) | [`putObject`](#putObject) | [`presignedPutObject`](#presignedPutObject) | [`setBucketPolicy`](#setBucketPolicy) | +| [`bucketExists`](#bucketExists) | [`copyObject`](#copyObject) | [`presignedPostPolicy`](#presignedPostPolicy) |[`setBucketNotification`](#setBucketNotification) | +| [`removeBucket`](#removeBucket) | [`statObject`](#statObject) | | [`getBucketNotification`](#getBucketNotification) | +| [`listObjects`](#listObjects) | [`removeObject`](#removeObject) | | [`removeAllBucketNotification`](#removeAllBucketNotification) | +| [`listIncompleteUploads`](#listIncompleteUploads) | [`removeObjects`](#removeObjects) | | | +| [`listenBucketNotifications`](#listenBucketNotifications) | [`removeIncompleteUpload`](#removeIncompleteUpload) | | | +| | [`selectObjectContent`](#selectObjectContent) | | | + +## 1. Constructors + + + +| | +|---| +|`public MinioClient(string endpoint, string accessKey = "", string secretKey = "", string region = "", string sessionToken="")` | +| Creates MinIO client object with given endpoint.AccessKey, secretKey, region and sessionToken are optional parameters, and can be omitted for anonymous access. + The client object uses Http access by default. To use Https, chain method WithSSL() to client object to use secure transfer protocol | + + +__Parameters__ + +| Param | Type | Description | +|---|---|---| +| `endpoint` | _string_ | endPoint is an URL, domain name, IPv4 address or IPv6 address.Valid endpoints are listed below: | +| | |s3.amazonaws.com | +| | |play.min.io | +| | |localhost | +| | |play.min.io| +| `accessKey` | _string_ |accessKey is like user-id that uniquely identifies your account.This field is optional and can be omitted for anonymous access. | +|`secretKey` | _string_ | secretKey is the password to your account.This field is optional and can be omitted for anonymous access.| +|`region` | _string_ | region to which calls should be made.This field is optional and can be omitted.| +|`sessionToken` | _string_ | sessionToken needs to be set if temporary access credentials are used | + +__Secure Access__ + +| | +|---| +|`Chain .WithSSL() to MinIO Client object to use https instead of http. ` | + +__Proxy__ + +| | +|---| +|`Chain .WithProxy(proxyObject) to MinIO Client object to use proxy ` | + +__Example__ + + +### MinIO + + +```cs +// 1. public MinioClient(String endpoint) +MinioClient minioClient = new MinioClient("play.min.io"); + +// 2. public MinioClient(String endpoint, String accessKey, String secretKey) +MinioClient minioClient = new MinioClient("play.min.io", + accessKey:"Q3AM3UQ867SPQQA43P2F", + secretKey:"zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG" + ).WithSSL(); + +// 3. Initializing minio client with proxy +IWebProxy proxy = new WebProxy("192.168.0.1", 8000); +MinioClient minioClient = new MinioClient("my-ip-address:9000", "minio", "minio123").WithSSL().WithProxy(proxy); + +// 4. Initializing minio client with temporary credentials +MinioClient minioClient = new MinioClient("my-ip-address:9000", "tempuserid", "temppasswd", sessionToken:"sessionToken"); +``` + + +### AWS S3 + + +```cs +// 1. public MinioClient(String endpoint) +MinioClient s3Client = new MinioClient("s3.amazonaws.com").WithSSL(); + +// 2. public MinioClient(String endpoint, String accessKey, String secretKey) +MinioClient s3Client = new MinioClient("s3.amazonaws.com:80", + accessKey:"YOUR-ACCESSKEYID", + secretKey:"YOUR-SECRETACCESSKEY").WithSSL(); +``` + +## 2. Bucket operations + + +### MakeBucketAsync(string bucketName, string location = "us-east-1") +`Task MakeBucketAsync(string bucketName, string location = "us-east-1", CancellationToken cancellationToken = default(CancellationToken))` + +Creates a new bucket. + + +__Parameters__ + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``region`` | _string_| Optional parameter. Defaults to us-east-1 for AWS requests | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``AccessDeniedException`` : upon access denial | +| | ``RedirectionException`` : upon redirection by server | +| | ``InternalClientException`` : upon internal library error | + + +__Example__ + + +```cs +try +{ + // Create bucket if it doesn't exist. + bool found = await minioClient.BucketExistsAsync("mybucket"); + if (found) + { + Console.WriteLine("mybucket already exists"); + } + else + { + // Create bucket 'my-bucketname'. + await minioClient.MakeBucketAsync("mybucket"); + Console.WriteLine("mybucket is created successfully"); + } +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### ListBucketsAsync() + +`Task ListBucketsAsync(CancellationToken cancellationToken = default(CancellationToken))` + +Lists all buckets. + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + +|Return Type | Exceptions | +|:--- |:--- | +| ``Task`` : Task with List of bucket type. | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``AccessDeniedException`` : upon access denial | +| | ``InvalidOperationException``: upon unsuccessful deserialization of xml data | +| | ``ErrorResponseException`` : upon unsuccessful execution | +| | ``InternalClientException`` : upon internal library error | + + +__Example__ + + +```cs +try +{ + // List buckets that have read access. + var list = await minioClient.ListBucketsAsync(); + foreach (Bucket bucket in list.Buckets) + { + Console.WriteLine(bucket.Name + " " + bucket.CreationDateDateTime); + } +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### BucketExistsAsync(string bucketName) + +`Task BucketExistsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))` + +Checks if a bucket exists. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket. | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` : true if the bucket exists | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``AccessDeniedException`` : upon access denial | +| | ``ErrorResponseException`` : upon unsuccessful execution | +| | ``InternalClientException`` : upon internal library error | + + + +__Example__ + + +```cs +try +{ + // Check whether 'my-bucketname' exists or not. + bool found = await minioClient.BucketExistsAsync(bucketName); + Console.WriteLine("bucket-name " + ((found == true) ? "exists" : "does not exist")); +} +catch (MinioException e) +{ + Console.WriteLine("[Bucket] Exception: {0}", e); +} +``` + + + +### RemoveBucketAsync(string bucketName) + +`Task RemoveBucketAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))` + +Removes a bucket. + + +NOTE: - removeBucket does not delete the objects inside the bucket. The objects need to be deleted using the removeObject API. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| Task | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``AccessDeniedException`` : upon access denial | +| | ``ErrorResponseException`` : upon unsuccessful execution | +| | ``InternalClientException`` : upon internal library error | +| | ``BucketNotFoundException`` : upon missing bucket | + + +__Example__ + + +```cs +try +{ + // Check if my-bucket exists before removing it. + bool found = await minioClient.BucketExistsAsync("mybucket"); + if (found) + { + // Remove bucket my-bucketname. This operation will succeed only if the bucket is empty. + await minioClient.RemoveBucketAsync("mybucket"); + Console.WriteLine("mybucket is removed successfully"); + } + else + { + Console.WriteLine("mybucket does not exist"); + } +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### ListObjectsAsync(string bucketName, string prefix = null, bool recursive = true) + +`IObservable ListObjectsAsync(string bucketName, string prefix = null, bool recursive = false, CancellationToken cancellationToken = default(CancellationToken))` + +Lists all objects in a bucket. + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``prefix`` | _string_ | Prefix string. List objects whose name starts with ``prefix`` | +| ``recursive`` | _bool_ | when false, emulates a directory structure where each listing returned is either a full object or part of the object's key up to the first '/'. All objects with the same prefix up to the first '/' will be merged into one entry. Defaults to `false`| +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +|Return Type | Exceptions | +|:--- |:--- | +| ``IObservable``:an Observable of Items. | _None_ | + + +__Example__ + + +```cs +try +{ + // Check whether 'mybucket' exists or not. + bool found = minioClient.BucketExistsAsync("mybucket"); + if (found) + { + // List objects from 'my-bucketname' + IObservable observable = minioClient.ListObjectsAsync("mybucket", "prefix", true); + IDisposable subscription = observable.Subscribe( + item => Console.WriteLine("OnNext: {0}", item.Key), + ex => Console.WriteLine("OnError: {0}", ex.Message), + () => Console.WriteLine("OnComplete: {0}")); + } + else + { + Console.WriteLine("mybucket does not exist"); + } +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + + +### ListIncompleteUploads(string bucketName, string prefix, bool recursive) + +`IObservable ListIncompleteUploads(string bucketName, string prefix, bool recursive, CancellationToken cancellationToken = default(CancellationToken))` + +Lists partially uploaded objects in a bucket. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``prefix`` | _string_ | Prefix string. List objects whose name starts with ``prefix`` | +| ``recursive`` | _bool_ | when false, emulates a directory structure where each listing returned is either a full object or part of the object's key up to the first '/'. All objects with the same prefix up to the first '/' will be merged into one entry | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +|Return Type | Exceptions | +|:--- |:--- | +| ``IObservable ``: an Observable of Upload. | _None_ | + + +__Example__ + + +```cs +try +{ + // Check whether 'mybucket' exist or not. + bool found = minioClient.BucketExistsAsync("mybucket"); + if (found) + { + // List all incomplete multipart upload of objects in 'mybucket' + IObservable observable = minioClient.ListIncompleteUploads("mybucket", "prefix", true); + IDisposable subscription = observable.Subscribe( + item => Console.WriteLine("OnNext: {0}", item.Key), + ex => Console.WriteLine("OnError: {0}", ex.Message), + () => Console.WriteLine("OnComplete: {0}")); + } + else + { + Console.WriteLine("mybucket does not exist"); + } +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + + +### ListenBucketNotificationsAsync(string bucketName, IList events, string prefix = "", string suffix = "") + +`IObservable ListenBucketNotificationsAsync(string bucketName, IList events, string prefix = "", string suffix = "", CancellationToken cancellationToken = default(CancellationToken))` + +Subscribes to bucket change notifications (a Minio-only extension) + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Bucket to get notifications from | +| ``events`` | _IList< EventType >_ | Events to listen for | +| ``prefix`` | _string_ | Filter keys starting with this prefix | +| ``suffix`` | _string_ | Filter keys ending with this suffix | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +|Return Type | Exceptions | +|:--- |:--- | +| ``IObservable``: an Observable of _MinioNotificationRaw_, which contain the raw JSON notifications. Use the _MinioNotification_ class to deserialise using the JSON library of your choice. | _None_ | + + +__Example__ + + +```cs +try +{ + var events = new List { EventType.ObjectCreatedAll }; + var prefix = null; + var suffix = null; + IObservable observable = minioClient.ListenBucketNotificationsAsync(bucketName, events, prefix, suffix); + + IDisposable subscription = observable.Subscribe( + notification => Console.WriteLine($"Notification: {notification.json}"), + ex => Console.WriteLine($"OnError: {ex}"), + () => Console.WriteLine($"Stopped listening for bucket notifications\n")); + +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### GetPolicyAsync(string bucketName) +`Task GetPolicyAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))` + +Get bucket policy. + + +__Parameters__ + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket. | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task``: The current bucket policy for given bucket as a json string. | Listed Exceptions: | +| | ``InvalidBucketNameException `` : upon invalid bucket name. | +| | ``InvalidObjectPrefixException`` : upon invalid object prefix. | +| | ``ConnectionException`` : upon connection error. | +| | ``AccessDeniedException`` : upon access denial | +| | ``InternalClientException`` : upon internal library error. | +| | ``BucketNotFoundException`` : upon missing bucket | + + +__Example__ + + +```cs +try +{ + String policyJson = await minioClient.GetPolicyAsync("myBucket"); + Console.WriteLine("Current policy: " + policy.GetType().ToString()); +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### SetPolicyAsync(string bucketName, string policyJson) +`Task SetPolicyAsync(string bucketName, string policyJson, CancellationToken cancellationToken = default(CancellationToken))` + +Set policy on bucket. + +__Parameters__ + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``policyJson`` | _string_ | Policy as a json string | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| Task | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | +| | ``InvalidBucketNameException `` : upon invalid bucket name | +| | ``InvalidObjectPrefixException`` : upon invalid object prefix | + + + +__Example__ + +```cs +try +{ + string policyJson = $@"{{""Version"":""2012-10-17"",""Statement"":[{{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}""],""Sid"":""""}},{{""Action"":[""s3:ListBucket""],""Condition"":{{""StringEquals"":{{""s3:prefix"":[""foo"",""prefix/""]}}}},""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}""],""Sid"":""""}},{{""Action"":[""s3:GetObject""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}/foo*"",""arn:aws:s3:::{bucketName}/prefix/*""],""Sid"":""""}}]}}"; + await minioClient.SetPolicyAsync("myBucket", policyJson); +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + + +### SetBucketNotificationAsync(string bucketName, BucketNotification notification) +`Task SetBucketNotificationAsync(string bucketName, BucketNotification notification, CancellationToken cancellationToken = default(CancellationToken))` + +Sets notification configuration for a given bucket + +__Parameters__ + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``notification`` | _BucketNotification_ | Notifications to apply | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| Task | Listed Exceptions: | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | +| | ``InvalidBucketNameException `` : upon invalid bucket name | +| | ``InvalidOperationException``: upon unsuccessful serialization of notification object | + + + +__Example__ +```cs +try +{ + BucketNotification notification = new BucketNotification(); + Arn topicArn = new Arn("aws", "sns", "us-west-1", "412334153608", "topicminio"); + + TopicConfig topicConfiguration = new TopicConfig(topicArn); + List events = new List(){ EventType.ObjectCreatedPut , EventType.ObjectCreatedCopy }; + topicConfiguration.AddEvents(events); + topicConfiguration.AddFilterPrefix("images"); + topicConfiguration.AddFilterSuffix("jpg"); + notification.AddTopic(topicConfiguration); + + QueueConfig queueConfiguration = new QueueConfig("arn:aws:sqs:us-west-1:482314153608:testminioqueue1"); + queueConfiguration.AddEvents(new List() { EventType.ObjectCreatedCompleteMultipartUpload }); + notification.AddQueue(queueConfiguration); + + await minio.SetBucketNotificationsAsync(bucketName, + notification); + Console.WriteLine("Notifications set for the bucket " + bucketName + " successfully"); +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### GetBucketNotificationAsync(string bucketName) +`Task GetBucketNotificationAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))` + +Get bucket notification configuration + + +__Parameters__ + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket. | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task``: The current notification configuration for the bucket. | Listed Exceptions: | +| | ``InvalidBucketNameException `` : upon invalid bucket name. | +| | ``ConnectionException`` : upon connection error. | +| | ``AccessDeniedException`` : upon access denial | +| | ``InternalClientException`` : upon internal library error. | +| | ``BucketNotFoundException`` : upon missing bucket | +| | ``InvalidOperationException``: upon unsuccessful deserialization of xml data | + + +__Example__ + + +```cs +try +{ + BucketNotification notifications = await minioClient.GetBucketNotificationAsync(bucketName); + Console.WriteLine("Notifications is " + notifications.ToXML()); +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### RemoveAllBucketNotificationsAsync(string bucketName) +`Task RemoveAllBucketNotificationsAsync(string bucketName, CancellationToken cancellationToken = default(CancellationToken))` + +Remove all notification configurations set on the bucket + + +__Parameters__ + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket. | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`: | Listed Exceptions: | +| | ``InvalidBucketNameException `` : upon invalid bucket name. | +| | ``ConnectionException`` : upon connection error. | +| | ``AccessDeniedException`` : upon access denial | +| | ``InternalClientException`` : upon internal library error. | +| | ``BucketNotFoundException`` : upon missing bucket | +| | ``InvalidOperationException``: upon unsuccessful serialization of xml data | + + +__Example__ + + +```cs +try +{ + await minioClient.RemoveAllBucketNotificationsAsync(bucketName); + Console.WriteLine("Notifications successfully removed from the bucket " + bucketName); +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + +## 3. Object operations + + +### GetObjectAsync(string bucketName, string objectName, Action callback, ServerSideEncryption sse) + +`Task GetObjectAsync(string bucketName, string objectName, Action callback, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` + +Downloads an object as a stream. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectName`` | _string_ | Object name in the bucket | +| ``callback`` | _Action_ | Call back to process stream | +| ``sse`` | _ServerSideEncryption_ | Server-side encryption option | Optional parameter. Defaults to null | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task``: Task callback returns an InputStream containing the object data. | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name. | +| | ``ConnectionException`` : upon connection error. | +| | ``InternalClientException`` : upon internal library error. | + + +__Example__ + + +```cs +try +{ + // Check whether the object exists using statObject(). + // If the object is not found, statObject() throws an exception, + // else it means that the object exists. + // Execution is successful. + await minioClient.StatObjectAsync("mybucket", "myobject"); + + // Get input stream to have content of 'my-objectname' from 'my-bucketname' + await minioClient.GetObjectAsync("mybucket", "myobject", + (stream) => + { + stream.CopyTo(Console.OpenStandardOutput()); + }); + } + catch (MinioException e) + { + Console.WriteLine("Error occurred: " + e); + } +``` + + +### GetObjectAsync(string bucketName, string objectName, long offset, long length, Action callback, ServerSideEncryption sse) + +`Task GetObjectAsync(string bucketName, string objectName, long offset, long length, Action callback, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` + +Downloads the specified range bytes of an object as a stream.Both offset and length are required. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket. | +| ``objectName`` | _string_ | Object name in the bucket. | +| ``offset``| _long_ | Offset of the object from where stream will start | +| ``length``| _long_| Length of the object to read in from the stream | +| ``callback`` | _Action_ | Call back to process stream | +| ``sse`` | _ServerSideEncryption_ | Server-side encryption option | Optional parameter. Defaults to null | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task``: Task callback returns an InputStream containing the object data. | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name. | +| | ``ConnectionException`` : upon connection error. | +| | ``InternalClientException`` : upon internal library error. | + + +__Example__ + + +```cs +try +{ + // Check whether the object exists using statObject(). + // If the object is not found, statObject() throws an exception, + // else it means that the object exists. + // Execution is successful. + await minioClient.StatObjectAsync("mybucket", "myobject"); + + // Get input stream to have content of 'my-objectname' from 'my-bucketname' + await minioClient.GetObjectAsync("mybucket", "myobject", 1024L, 10L, + (stream) => + { + stream.CopyTo(Console.OpenStandardOutput()); + }); + } + catch (MinioException e) + { + Console.WriteLine("Error occurred: " + e); + } +``` + + +### GetObjectAsync(String bucketName, String objectName, String fileName, ServerSideEncryption sse) + +`Task GetObjectAsync(string bucketName, string objectName, string fileName, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` + +Downloads and saves the object as a file in the local filesystem. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _String_ | Name of the bucket | +| ``objectName`` | _String_ | Object name in the bucket | +| ``fileName`` | _String_ | File name | +| ``sse`` | _ServerSideEncryption_ | Server-side encryption option | Optional parameter. Defaults to null | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task `` | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | + +__Example__ + +```cs +try +{ + // Check whether the object exists using statObjectAsync(). + // If the object is not found, statObjectAsync() throws an exception, + // else it means that the object exists. + // Execution is successful. + await minioClient.StatObjectAsync("mybucket", "myobject"); + + // Gets the object's data and stores it in photo.jpg + await minioClient.GetObjectAsync("mybucket", "myobject", "photo.jpg"); + +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + +### PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType, ServerSideEncryption sse) + +` Task PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType, Dictionary metaData = null, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` + + +Uploads contents from a stream to objectName. + + + +__Parameters__ + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectName`` | _string_ | Object name in the bucket | +| ``data`` | _Stream_ | Stream to upload | +| ``size`` | _long_ | size of stream | +| ``contentType`` | _string_ | Content type of the file. Defaults to "application/octet-stream" | +| ``metaData`` | _Dictionary_ | Dictionary of metadata headers. Defaults to null. | +| ``sse`` | _ServerSideEncryption_ | Server-side encryption option | Optional parameter. Defaults to null | + +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | +| | ``EntityTooLargeException``: upon proposed upload size exceeding max allowed | +| | ``UnexpectedShortReadException``: data read was shorter than size of input buffer | +| | ``ArgumentNullException``: upon null input stream | + +__Example__ + + +The maximum size of a single object is limited to 5TB. putObject transparently uploads objects larger than 5MiB in multiple parts. Uploaded data is carefully verified using MD5SUM signatures. + + +```cs +try +{ + byte[] bs = File.ReadAllBytes(fileName); + System.IO.MemoryStream filestream = new System.IO.MemoryStream(bs); + // Specify SSE-C encryption options + Aes aesEncryption = Aes.Create(); + aesEncryption.KeySize = 256; + aesEncryption.GenerateKey(); + var ssec = new SSEC(aesEncryption.Key); + await minio.PutObjectAsync("mybucket", + "island.jpg", + filestream, + filestream.Length, + "application/octet-stream", ssec); + Console.WriteLine("island.jpg is uploaded successfully"); +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### PutObjectAsync(string bucketName, string objectName, string filePath, string contentType=null, ServerSideEncryption sse) + +` Task PutObjectAsync(string bucketName, string objectName, string filePath, string contentType = null, Dictionary metaData = null, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` + + +Uploads contents from a file to objectName. + + + +__Parameters__ + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectName`` | _string_ | Object name in the bucket | +| ``fileName`` | _string_ | File to upload | +| ``contentType`` | _string_ | Content type of the file. Defaults to " | +| ``metadata`` | _Dictionary_ | Dictionary of meta data headers and their values.Defaults to null.| +| ``sse`` | _ServerSideEncryption_ | Server-side encryption option | Optional parameter. Defaults to null | + +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | +| | ``EntityTooLargeException``: upon proposed upload size exceeding max allowed | + +__Example__ + + +The maximum size of a single object is limited to 5TB. putObject transparently uploads objects larger than 5MiB in multiple parts. Uploaded data is carefully verified using MD5SUM signatures. + + +```cs +try +{ + await minio.PutObjectAsync("mybucket", "island.jpg", "/mnt/photos/island.jpg", contentType: "application/octet-stream"); + Console.WriteLine("island.jpg is uploaded successfully"); +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + +### StatObjectAsync(string bucketName, string objectName, ServerSideEncryption sse) + +`Task StatObjectAsync(string bucketName, string objectName, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken))` + +Gets metadata of an object. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectName`` | _string_ | Object name in the bucket | +| ``sse`` | _ServerSideEncryption_ | Server-side encryption option | Optional parameter. Defaults to null | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task``: Populated object meta data. | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | + + + +__Example__ + + +```cs +try +{ + // Get the metadata of the object. + ObjectStat objectStat = await minioClient.StatObjectAsync("mybucket", "myobject"); + Console.WriteLine(objectStat); +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null, Dictionary metadata = null, ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null) + +*`Task CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null, Dictionary metadata = null, ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null, CancellationToken cancellationToken = default(CancellationToken))`* + +Copies content from objectName to destObjectName. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the source bucket | +| ``objectName`` | _string_ | Object name in the source bucket to be copied | +| ``destBucketName`` | _string_ | Destination bucket name | +| ``destObjectName`` | _string_ | Destination object name to be created, if not provided defaults to source object name| +| ``copyConditions`` | _CopyConditions_ | Map of conditions useful for applying restrictions on copy operation| +| ``metadata`` | _Dictionary_ | Dictionary of meta data headers and their values on the destination side.Defaults to null.| +| ``sseSrc`` | _ServerSideEncryption_ | Server-side encryption option for source object | Optional parameter. Defaults to null | +| ``sseDest`` | _ServerSideEncryption_ | Server-side encryption option for destination object| Optional parameter. Defaults to null | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | +| | ``ArgumentException`` : upon missing bucket/object names | + +__Example__ + + +This API performs a Server-side copy operation from a given source object to destination object. + +```cs +try +{ + CopyConditions copyConditions = new CopyConditions(); + copyConditions.setMatchETagNone("TestETag"); + ServerSideEncryption sseSrc, sseDst; + // Uncomment to specify source and destination Server-side encryption options + /* + Aes aesEncryption = Aes.Create(); + aesEncryption.KeySize = 256; + aesEncryption.GenerateKey(); + sseSrc = new SSEC(aesEncryption.Key); + sseDst = new SSES3(); + */ + await minioClient.CopyObjectAsync("mybucket", "island.jpg", "mydestbucket", "processed.png", copyConditions, sseSrc:sseSrc, sseDest:sseDst); + Console.WriteLine("island.jpg is uploaded successfully"); +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### RemoveObjectAsync(string bucketName, string objectName) + +`Task RemoveObjectAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken))` + +Removes an object. + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectName`` | _string_ | Object name in the bucket | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | + + + +__Example__ + + +```cs +try +{ + // Remove objectname from the bucket my-bucketname. + await minioClient.RemoveObjectAsync("mybucket", "myobject"); + Console.WriteLine("successfully removed mybucket/myobject"); +} +catch (MinioException e) +{ + Console.WriteLine("Error: " + e); +} +``` + +### RemoveObjectAsync(string bucketName, IEnumerable objectsList) + +`Task> RemoveObjectAsync(string bucketName, IEnumerable objectsList, CancellationToken cancellationToken = default(CancellationToken))` + +Removes a list of objects. + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectsList`` | _IEnumerable_ | IEnumerable of Object names | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | + + + +__Example__ + + +```cs +try +{ + List objectNames = new LinkedList(); + objectNames.add("my-objectname1"); + objectNames.add("my-objectname2"); + objectNames.add("my-objectname3"); + // Remove list of objects in objectNames from the bucket bucketName. + IObservable observable = await minio.RemoveObjectAsync(bucketName, objectNames); + IDisposable subscription = observable.Subscribe( + deleteError => Console.WriteLine("Object: {0}", deleteError.Key), + ex => Console.WriteLine("OnError: {0}", ex), + () => + { + Console.WriteLine("Listed all delete errors for remove objects on " + bucketName + "\n"); + }); +} +catch (MinioException e) +{ + Console.WriteLine("Error: " + e); +} +``` + + +### RemoveIncompleteUploadAsync(string bucketName, string objectName) + +`Task RemoveIncompleteUploadAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken))` + +Removes a partially uploaded object. + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectName`` | _string_ | Object name in the bucket | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InternalClientException`` : upon internal library error | + + +__Example__ + + +```cs +try +{ + // Removes partially uploaded objects from buckets. + await minioClient.RemoveIncompleteUploadAsync("mybucket", "myobject"); + Console.WriteLine("successfully removed all incomplete upload session of my-bucketname/my-objectname"); +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### SelectObjectContentAsync(string bucketName, string objectName, SelectObjectOptions opts) + +`Task SelectObjectContentAsync(string bucketName, string objectName, SelectObjectOptions opts, CancellationToken cancellationToken = default(CancellationToken))` + +Downloads an object as a stream. + + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectName`` | _string_ | Object name in the bucket | +| ``opts`` | SelectObjectOptions | options for SelectObjectContent async | Required parameter. | +| ``cancellationToken``| _System.Threading.CancellationToken_ | Optional parameter. Defaults to default(CancellationToken) | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task``: Task callback returns a SelectResponseStream containing select results. | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name. | +| | ``ConnectionException`` : upon connection error. | +| | ``InternalClientException`` : upon internal library error. | +| | ``ArgumentException`` : upon invalid response format | +| | ``IOException`` : insufficient data | + + +__Example__ + + +```cs +try +{ + var opts = new SelectObjectOptions() + { + ExpressionType = QueryExpressionType.SQL, + Expression = "select count(*) from s3object", + InputSerialization = new SelectObjectInputSerialization() + { + CompressionType = SelectCompressionType.NONE, + CSV = new CSVInputOptions() + { + FileHeaderInfo = CSVFileHeaderInfo.None, + RecordDelimiter = "\n", + FieldDelimiter = ",", + } + }, + OutputSerialization = new SelectObjectOutputSerialization() + { + CSV = new CSVOutputOptions() + { + RecordDelimiter = "\n", + FieldDelimiter = ",", + } + } + }; + + var resp = await minio.SelectObjectContentAsync(bucketName, objectName, opts); + resp.Payload.CopyTo(Console.OpenStandardOutput()); + Console.WriteLine("Bytes scanned:" + resp.Stats.BytesScanned); + Console.WriteLine("Bytes returned:" + resp.Stats.BytesReturned); + Console.WriteLine("Bytes processed:" + resp.Stats.BytesProcessed); + if (resp.Progress != null) + { + Console.WriteLine("Progress :" + resp.Progress.BytesProcessed); + } +} +catch (MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + +## 4. Presigned operations + + +### PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null, DateTime? reqDate = null); +`Task PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary reqParams = null, DateTime? reqDate = null)` + +Generates a presigned URL for HTTP GET operations. Browsers/Mobile clients may point to this URL to directly download objects even if the bucket is private. This presigned URL can have an associated expiration time in seconds after which it is no longer operational. The default expiry is set to 7 days. + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _String_ | Name of the bucket | +| ``objectName`` | _String_ | Object name in the bucket | +| ``expiresInt`` | _Integer_ | Expiry in seconds. Default expiry is set to 7 days. | +| ``reqParams`` | _Dictionary_ | Additional response header overrides supports response-expires, response-content-type, response-cache-control, response-content-disposition.| +| ``reqDate`` | _DateTime?_ | Optional request date and time. Defaults to DateTime.UtcNow if unset.| + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` : string contains URL to download the object | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``InvalidExpiryRangeException`` : upon invalid expiry range. | + + +__Example__ + + +```cs +try +{ + String url = await minioClient.PresignedGetObjectAsync("mybucket", "myobject", 60 * 60 * 24); + Console.WriteLine(url); +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### PresignedPutObjectAsync(string bucketName, string objectName, int expiresInt) + +`Task PresignedPutObjectAsync(string bucketName, string objectName, int expiresInt)` + +Generates a presigned URL for HTTP PUT operations. Browsers/Mobile clients may point to this URL to upload objects directly to a bucket even if it is private. This presigned URL can have an associated expiration time in seconds after which it is no longer operational. The default expiry is set to 7 days. + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``bucketName`` | _string_ | Name of the bucket | +| ``objectName`` | _string_ | Object name in the bucket | +| ``expiresInt`` | _int_ | Expiry in seconds. Default expiry is set to 7 days. | + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task`` : string contains URL to upload the object | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``InvalidKeyException`` : upon an invalid access key or secret key | +| | ``ConnectionException`` : upon connection error | +| | ``InvalidExpiryRangeException`` : upon invalid expiry range. | + + +__Example__ + +```cs +try +{ + String url = await minioClient.PresignedPutObjectAsync("mybucket", "myobject", 60 * 60 * 24); + Console.WriteLine(url); +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` + + +### PresignedPostPolicy(PostPolicy policy) + +`Task> PresignedPostPolicyAsync(PostPolicy policy)` + +Allows setting policy conditions to a presigned URL for POST operations. Policies such as bucket name to receive object uploads, key name prefixes, expiry policy may be set. + +__Parameters__ + + +|Param | Type | Description | +|:--- |:--- |:--- | +| ``PostPolicy`` | _PostPolicy_ | Post policy of an object. | + + +| Return Type | Exceptions | +|:--- |:--- | +| ``Task>``: Map of strings to construct form-data. | Listed Exceptions: | +| | ``InvalidBucketNameException`` : upon invalid bucket name | +| | ``ConnectionException`` : upon connection error | +| | ``NoSuchAlgorithmException`` : upon requested algorithm was not found during signature calculation. | + + + +__Example__ + + +```cs +try +{ + PostPolicy policy = new PostPolicy(); + policy.SetContentType("image/png"); + policy.SetUserMetadata("custom", "user"); + DateTime expiration = DateTime.UtcNow; + policy.SetExpires(expiration.AddDays(10)); + policy.SetKey("my-objectname"); + policy.SetBucket("my-bucketname"); + + Dictionary formData = minioClient.Api.PresignedPostPolicy(policy); + string curlCommand = "curl "; + foreach (KeyValuePair pair in formData) + { + curlCommand = curlCommand + " -F " + pair.Key + "=" + pair.Value; + } + curlCommand = curlCommand + " -F file=@/etc/bashrc https://s3.amazonaws.com/my-bucketname"; + Console.WriteLine(curlCommand); +} +catch(MinioException e) +{ + Console.WriteLine("Error occurred: " + e); +} +``` +## Client Custom Settings + +### SetAppInfo(string appName, string appVersion) +Adds application details to User-Agent. + +__Parameters__ + +| Param | Type | Description | +|---|---|---| +|`appName` | _string_ | Name of the application performing the API requests | +| `appVersion`| _string_ | Version of the application performing the API requests | + + +__Example__ + + +```cs +// Set Application name and version to be used in subsequent API requests. +minioClient.SetAppInfo("myCloudApp", "1.0.0") +``` + +### SetTraceOn(IRequestLogger logger = null) +Enables HTTP tracing. The trace is written to the stdout. + +__Parameters__ + +| Param | Type | Description | +|---|---|---| +|`logger` | _IRequestLogger_ | Implementation of interface `Minio.IRequestLogger` for serialization models for trace HTTP | + +__Example__ + +```cs +// Set HTTP tracing on with default trace logger. +minioClient.SetTraceOn() + +// Set custom logger for HTTP trace +minioClient.SetTraceOn(new JsonNetLogger()) +``` + + + +### SetTraceOff() +Disables HTTP tracing. + + +__Example__ +```cs +// Sets HTTP tracing off. +minioClient.SetTraceOff() +``` diff --git a/source/sdk/dotnet/minio-dotnet.rst b/source/sdk/dotnet/minio-dotnet.rst new file mode 100644 index 00000000..7df110d6 --- /dev/null +++ b/source/sdk/dotnet/minio-dotnet.rst @@ -0,0 +1,10 @@ +.. _minio-dotnet: + +.. default-domain:: minio + +.. contents:: Table of Contents + :local: + :depth: 2 + +.. include:: /sdk/dotnet/API.md + :parser: myst_parser.sphinx_ diff --git a/source/sdk/go/API.md b/source/sdk/go/API.md new file mode 100644 index 00000000..39299976 --- /dev/null +++ b/source/sdk/go/API.md @@ -0,0 +1,2112 @@ +# MinIO Go Client API Reference [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +## Initialize MinIO Client object. + +## MinIO + +```go +package main + +import ( + "log" + + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" +) + +func main() { + endpoint := "play.min.io" + accessKeyID := "Q3AM3UQ867SPQQA43P2F" + secretAccessKey := "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG" + useSSL := true + + // Initialize minio client object. + minioClient, err := minio.New(endpoint, &minio.Options{ + Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""), + Secure: useSSL, + }) + if err != nil { + log.Fatalln(err) + } + + log.Printf("%#v\n", minioClient) // minioClient is now setup +} +``` + +## AWS S3 + +```go +package main + +import ( + "fmt" + + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" +) + +func main() { + // Initialize minio client object. + s3Client, err := minio.New("s3.amazonaws.com", &minio.Options{ + Creds: credentials.NewStaticV4("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""), + Secure: true, + }) + if err != nil { + fmt.Println(err) + return + } +} +``` + +| Bucket operations | Object operations | Presigned operations | Bucket Policy/Notification Operations | Client custom settings | +| :--- | :--- | :--- | :--- | :--- | +| [`MakeBucket`](#MakeBucket) | [`GetObject`](#GetObject) | [`PresignedGetObject`](#PresignedGetObject) | [`SetBucketPolicy`](#SetBucketPolicy) | [`SetAppInfo`](#SetAppInfo) | +| | [`PutObject`](#PutObject) | [`PresignedPutObject`](#PresignedPutObject) | [`GetBucketPolicy`](#GetBucketPolicy) | | +| [`ListBuckets`](#ListBuckets) | [`CopyObject`](#CopyObject) | [`PresignedHeadObject`](#PresignedHeadObject) | [`SetBucketNotification`](#SetBucketNotification) | [`TraceOn`](#TraceOn) | +| [`BucketExists`](#BucketExists) | [`StatObject`](#StatObject) | [`PresignedPostPolicy`](#PresignedPostPolicy) | [`GetBucketNotification`](#GetBucketNotification) | [`TraceOff`](#TraceOff) | +| [`RemoveBucket`](#RemoveBucket) | [`RemoveObject`](#RemoveObject) | | [`RemoveAllBucketNotification`](#RemoveAllBucketNotification) | [`SetS3TransferAccelerate`](#SetS3TransferAccelerate) | +| [`ListObjects`](#ListObjects) | [`RemoveObjects`](#RemoveObjects) | | [`ListenBucketNotification`](#ListenBucketNotification) | | +| | [`RemoveIncompleteUpload`](#RemoveIncompleteUpload) | | [`SetBucketLifecycle`](#SetBucketLifecycle) | | +| [`ListIncompleteUploads`](#ListIncompleteUploads) | [`FPutObject`](#FPutObject) | | [`GetBucketLifecycle`](#GetBucketLifecycle) | | +| [`SetBucketTagging`](#SetBucketTagging) | [`FGetObject`](#FGetObject) | | [`SetObjectLockConfig`](#SetObjectLockConfig) | | +| [`GetBucketTagging`](#GetBucketTagging) | [`ComposeObject`](#ComposeObject) | | [`GetObjectLockConfig`](#GetObjectLockConfig) | | +| [`RemoveBucketTagging`](#RemoveBucketTagging) | | | [`EnableVersioning`](#EnableVersioning) | | +| [`SetBucketReplication`](#SetBucketReplication) | | | [`DisableVersioning`](#DisableVersioning) | | +| [`GetBucketReplication`](#GetBucketReplication) | [`PutObjectRetention`](#PutObjectRetention) | | [`GetBucketEncryption`](#GetBucketEncryption) | | +| [`RemoveBucketReplication`](#RemoveBucketReplication) | [`GetObjectRetention`](#GetObjectRetention) | | [`RemoveBucketEncryption`](#RemoveBucketEncryption) | | +| | [`PutObjectLegalHold`](#PutObjectLegalHold) | | | | +| | [`GetObjectLegalHold`](#GetObjectLegalHold) | | | | +| | [`SelectObjectContent`](#SelectObjectContent) | | | | +| | [`PutObjectTagging`](#PutObjectTagging) | | | | +| | [`GetObjectTagging`](#GetObjectTagging) | | | | +| | [`RemoveObjectTagging`](#RemoveObjectTagging) | | | | +| | [`RestoreObject`](#RestoreObject) | | | | + +## 1. Constructor + + +### New(endpoint string, opts \*Options) (\*Client, error) +Initializes a new client object. + +__Parameters__ + +| Param | Type | Description | +|:-----------|:----------------|:--------------------------------------| +| `endpoint` | _string_ | S3 compatible object storage endpoint | +| `opts` | _minio.Options_ | Options for constructing a new client | + +__minio.Options__ + +| Field | Type | Description | +|:--------------------|:---------------------------|:-----------------------------------------------------------------------------| +| `opts.Creds` | _*credentials.Credentials_ | S3 compatible object storage access credentials | +| `opts.Secure` | _bool_ | If 'true' API requests will be secure (HTTPS), and insecure (HTTP) otherwise | +| `opts.Transport` | _http.RoundTripper_ | Custom transport for executing HTTP transactions | +| `opts.Region` | _string_ | S3 compatible object storage region | +| `opts.BucketLookup` | _BucketLookupType_ | Bucket lookup type can be one of the following values | +| | | _minio.BucketLookupDNS_ | +| | | _minio.BucketLookupPath_ | +| | | _minio.BucketLookupAuto_ | + +## 2. Bucket operations + + +### MakeBucket(ctx context.Context, bucketName string, opts MakeBucketOptions) +Creates a new bucket. + +__Parameters__ + +| Param | Type | Description | +|--------------|---------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `ctx` | _context.Context_ | Custom context for timeout/cancellation of the call | +| `bucketName` | _string_ | Name of the bucket | +| `opts` | _minio.MakeBucketOptions_ | Bucket options such as `Region` where the bucket is to be created. Default value is us-east-1. Other valid values are listed below. Note: When used with minio server, use the region specified in its config file (defaults to us-east-1). | +| | | us-east-1 | +| | | us-east-2 | +| | | us-west-1 | +| | | us-west-2 | +| | | ca-central-1 | +| | | eu-west-1 | +| | | eu-west-2 | +| | | eu-west-3 | +| | | eu-central-1 | +| | | eu-north-1 | +| | | ap-east-1 | +| | | ap-south-1 | +| | | ap-southeast-1 | +| | | ap-southeast-2 | +| | | ap-northeast-1 | +| | | ap-northeast-2 | +| | | ap-northeast-3 | +| | | me-south-1 | +| | | sa-east-1 | +| | | us-gov-west-1 | +| | | us-gov-east-1 | +| | | cn-north-1 | +| | | cn-northwest-1 | + + +__Example__ + + +```go +// Create a bucket at region 'us-east-1' with object locking enabled. +err = minioClient.MakeBucket(context.Background(), "mybucket", minio.MakeBucketOptions{Region: "us-east-1", ObjectLocking: true}) +if err != nil { + fmt.Println(err) + return +} +fmt.Println("Successfully created mybucket.") +``` + + +### ListBuckets(ctx context.Context) ([]BucketInfo, error) +Lists all buckets. + +| Param | Type | Description | +|---|---|---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketList` | _[]minio.BucketInfo_ | Lists of all buckets | + + +__minio.BucketInfo__ + +| Field | Type | Description | +|---|---|---| +|`bucket.Name` | _string_ | Name of the bucket | +|`bucket.CreationDate` | _time.Time_ | Date of bucket creation | + + +__Example__ + + +```go +buckets, err := minioClient.ListBuckets(context.Background()) +if err != nil { + fmt.Println(err) + return +} +for _, bucket := range buckets { + fmt.Println(bucket) +} +``` + + +### BucketExists(ctx context.Context, bucketName string) (found bool, err error) +Checks if a bucket exists. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`found` | _bool_ | Indicates whether bucket exists or not | +|`err` | _error_ | Standard Error | + + +__Example__ + + +```go +found, err := minioClient.BucketExists(context.Background(), "mybucket") +if err != nil { + fmt.Println(err) + return +} +if found { + fmt.Println("Bucket found") +} +``` + + +### RemoveBucket(ctx context.Context, bucketName string) error +Removes a bucket, bucket should be empty to be successfully removed. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Example__ + + +```go +err = minioClient.RemoveBucket(context.Background(), "mybucket") +if err != nil { + fmt.Println(err) + return +} +``` + + +### ListObjects(ctx context.Context, bucketName string, opts ListObjectsOptions) <-chan ObjectInfo +Lists objects in a bucket. + +__Parameters__ + + +| Param | Type | Description | +|:-------------|:---------------------------|:----------------------------------------------------| +| `ctx` | _context.Context_ | Custom context for timeout/cancellation of the call | +| `bucketName` | _string_ | Name of the bucket | +| `opts` | _minio.ListObjectsOptions_ | Options per to list objects | + + +__Return Value__ + +|Param |Type |Description | +|:---|:---| :---| +|`objectInfo` | _chan minio.ObjectInfo_ |Read channel for all objects in the bucket, the object is of the format listed below: | + +__minio.ObjectInfo__ + +|Field |Type |Description | +|:---|:---| :---| +|`objectInfo.Key` | _string_ |Name of the object | +|`objectInfo.Size` | _int64_ |Size of the object | +|`objectInfo.ETag` | _string_ |MD5 checksum of the object | +|`objectInfo.LastModified` | _time.Time_ |Time when object was last modified | + + +```go +ctx, cancel := context.WithCancel(context.Background()) + +defer cancel() + +objectCh := minioClient.ListObjects(ctx, "mybucket", minio.ListObjectsOptions{ + Prefix: "myprefix", + Recursive: true, +}) +for object := range objectCh { + if object.Err != nil { + fmt.Println(object.Err) + return + } + fmt.Println(object) +} +``` + + + +### ListIncompleteUploads(ctx context.Context, bucketName, prefix string, recursive bool) <- chan ObjectMultipartInfo +Lists partially uploaded objects in a bucket. + + +__Parameters__ + + +| Param | Type | Description | +|:-------------|:------------------|:---------------------------------------------------------------------------------------------------------| +| `ctx` | _context.Context_ | Custom context for timeout/cancellation of the call | +| `bucketName` | _string_ | Name of the bucket | +| `prefix` | _string_ | Prefix of objects that are partially uploaded | +| `recursive` | _bool_ | `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. | + + +__Return Value__ + +|Param |Type |Description | +|:---|:---| :---| +|`multiPartInfo` | _chan minio.ObjectMultipartInfo_ |Emits multipart objects of the format listed below: | + +__minio.ObjectMultipartInfo__ + +|Field |Type |Description | +|:---|:---| :---| +|`multiPartObjInfo.Key` | _string_ |Name of incompletely uploaded object | +|`multiPartObjInfo.UploadID` | _string_ |Upload ID of incompletely uploaded object | +|`multiPartObjInfo.Size` | _int64_ |Size of incompletely uploaded object | + +__Example__ + + +```go +isRecursive := true // Recursively list everything at 'myprefix' +multiPartObjectCh := minioClient.ListIncompleteUploads(context.Background(), "mybucket", "myprefix", isRecursive) +for multiPartObject := range multiPartObjectCh { + if multiPartObject.Err != nil { + fmt.Println(multiPartObject.Err) + return + } + fmt.Println(multiPartObject) +} +``` + + +### SetBucketTagging(ctx context.Context, bucketName string, tags *tags.Tags) error +Sets tags to a bucket. + + +__Parameters__ + +| Param | Type | Description | +|:-------------|:------------------|:----------------------------------------------------| +| `ctx` | _context.Context_ | Custom context for timeout/cancellation of the call | +| `bucketName` | _string_ | Name of the bucket | +| `tags` | _*tags.Tags_ | Bucket tags | + +__Example__ +```go +// Create tags from a map. +tags, err := tags.NewTags(map[string]string{ + "Tag1": "Value1", + "Tag2": "Value2", +}, false) +if err != nil { + log.Fatalln(err) +} + +err = minioClient.SetBucketTagging(context.Background(), "my-bucketname", tags) +if err != nil { + log.Fatalln(err) +} +``` + + +### GetBucketTagging(ctx context.Context, bucketName string) (*tags.Tags, error) +Gets tags of a bucket. + + +__Parameters__ + +| Param | Type | Description | +|:-------------|:-------------|:-------------------| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +| `bucketName` | _string_ | Name of the bucket | + +__Return Value__ + +| Param | Type | Description | +|:-------|:-------------|:------------| +| `tags` | _*tags.Tags_ | Bucket tags | + +__Example__ +```go +tags, err := minioClient.GetBucketTagging(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} + +fmt.Printf("Fetched Object Tags: %v\n", tags) +``` + + +### RemoveBucketTagging(ctx context.Context, bucketName string) error +Removes all tags on a bucket. + + +__Parameters__ + +| Param | Type | Description | +|:-------------|:-------------|:-------------------| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +| `bucketName` | _string_ | Name of the bucket | + +__Example__ +```go +err := minioClient.RemoveBucketTagging(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +``` + +## 3. Object operations + + +### GetObject(ctx context.Context, bucketName, objectName string, opts GetObjectOptions) (*Object, error) +Returns a stream of the object data. Most of the common errors occur when reading the stream. + + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`opts` | _minio.GetObjectOptions_ | Options for GET requests specifying additional options like encryption, If-Match | + + +__minio.GetObjectOptions__ + +|Field | Type | Description | +|:---|:---|:---| +| `opts.ServerSideEncryption` | _encrypt.ServerSide_ | Interface provided by `encrypt` package to specify server-side-encryption. (For more information see https://godoc.org/github.com/minio/minio-go/v7) | +| `opts.Internal` | _minio.AdvancedGetOptions_ | This option is intended for internal use by MinIO server. This option should not be set unless the application is aware of intended use. +__Return Value__ + + +|Param |Type |Description | +|:---|:---| :---| +|`object` | _*minio.Object_ |_minio.Object_ represents object reader. It implements io.Reader, io.Seeker, io.ReaderAt and io.Closer interfaces. | + + +__Example__ + + +```go +object, err := minioClient.GetObject(context.Background(), "mybucket", "myobject", minio.GetObjectOptions{}) +if err != nil { + fmt.Println(err) + return +} +localFile, err := os.Create("/tmp/local-file.jpg") +if err != nil { + fmt.Println(err) + return +} +if _, err = io.Copy(localFile, object); err != nil { + fmt.Println(err) + return +} +``` + + +### FGetObject(ctx context.Context, bucketName, objectName, filePath string, opts GetObjectOptions) error +Downloads and saves the object as a file in the local filesystem. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`filePath` | _string_ |Path to download object to | +|`opts` | _minio.GetObjectOptions_ | Options for GET requests specifying additional options like encryption, If-Match | + + +__Example__ + + +```go +err = minioClient.FGetObject(context.Background(), "mybucket", "myobject", "/tmp/myobject", minio.GetObjectOptions{}) +if err != nil { + fmt.Println(err) + return +} +``` + + +### PutObject(ctx context.Context, bucketName, objectName string, reader io.Reader, objectSize int64,opts PutObjectOptions) (info UploadInfo, err error) +Uploads objects that are less than 128MiB in a single PUT operation. For objects that are greater than 128MiB in size, PutObject seamlessly uploads the object as parts of 128MiB or more depending on the actual file size. The max upload size for an object is 5TB. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`reader` | _io.Reader_ |Any Go type that implements io.Reader | +|`objectSize`| _int64_ |Size of the object being uploaded. Pass -1 if stream size is unknown | +|`opts` | _minio.PutObjectOptions_ | Allows user to set optional custom metadata, content headers, encryption keys and number of threads for multipart upload operation. | + +__minio.PutObjectOptions__ + +| Field | Type | Description | +|:-------------------------------|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `opts.UserMetadata` | _map[string]string_ | Map of user metadata | +| `opts.UserTags` | _map[string]string_ | Map of user object tags | +| `opts.Progress` | _io.Reader_ | Reader to fetch progress of an upload | +| `opts.ContentType` | _string_ | Content type of object, e.g "application/text" | +| `opts.ContentEncoding` | _string_ | Content encoding of object, e.g "gzip" | +| `opts.ContentDisposition` | _string_ | Content disposition of object, "inline" | +| `opts.ContentLanguage` | _string_ | Content language of object, e.g "French" | +| `opts.CacheControl` | _string_ | Used to specify directives for caching mechanisms in both requests and responses e.g "max-age=600" | +| `opts.Mode` | _*minio.RetentionMode_ | Retention mode to be set, e.g "COMPLIANCE" | +| `opts.RetainUntilDate` | _*time.Time_ | Time until which the retention applied is valid | +| `opts.ServerSideEncryption` | _encrypt.ServerSide_ | Interface provided by `encrypt` package to specify server-side-encryption. (For more information see https://godoc.org/github.com/minio/minio-go/v7) | +| `opts.StorageClass` | _string_ | Specify storage class for the object. Supported values for MinIO server are `REDUCED_REDUNDANCY` and `STANDARD` | +| `opts.WebsiteRedirectLocation` | _string_ | Specify a redirect for the object, to another object in the same bucket or to a external URL. | +| `opts.SendContentMd5` | _bool_ | Specify if you'd like to send `content-md5` header with PutObject operation. Note that setting this flag will cause higher memory usage because of in-memory `md5sum` calculation. | +| `opts.PartSize` | _uint64_ | Specify a custom part size used for uploading the object | +| `opts.Internal` | _minio.AdvancedPutOptions_ | This option is intended for internal use by MinIO server and should not be set unless the application is aware of intended use. +| +__minio.UploadInfo__ + +| Field | Type | Description | +|:--------------------|:---------|:-------------------------------------------| +| `info.ETag` | _string_ | The ETag of the new object | +| `info.VersionID` | _string_ | The version identifyer of the new object | + + +__Example__ + + +```go +file, err := os.Open("my-testfile") +if err != nil { + fmt.Println(err) + return +} +defer file.Close() + +fileStat, err := file.Stat() +if err != nil { + fmt.Println(err) + return +} + +uploadInfo, err := minioClient.PutObject(context.Background(), "mybucket", "myobject", file, fileStat.Size(), minio.PutObjectOptions{ContentType:"application/octet-stream"}) +if err != nil { + fmt.Println(err) + return +} +fmt.Println("Successfully uploaded bytes: ", uploadInfo) +``` + +API methods PutObjectWithSize, PutObjectWithMetadata, PutObjectStreaming, and PutObjectWithProgress available in minio-go SDK release v3.0.3 are replaced by the new PutObject call variant that accepts a pointer to PutObjectOptions struct. + + + +### CopyObject(ctx context.Context, dst CopyDestOptions, src CopySrcOptions) (UploadInfo, error) +Create or replace an object through server-side copying of an existing object. It supports conditional copying, copying a part of an object and server-side encryption of destination and decryption of source. See the `CopySrcOptions` and `DestinationInfo` types for further details. + +To copy multiple source objects into a single destination object see the `ComposeObject` API. + +__Parameters__ + +| Param | Type | Description | +|:------|:------------------------|:----------------------------------------------------| +| `ctx` | _context.Context_ | Custom context for timeout/cancellation of the call | +| `dst` | _minio.CopyDestOptions_ | Argument describing the destination object | +| `src` | _minio.CopySrcOptions_ | Argument describing the source object | + + +__minio.UploadInfo__ + +| Field | Type | Description | +|:-----------------|:---------|:-----------------------------------------| +| `info.ETag` | _string_ | The ETag of the new object | +| `info.VersionID` | _string_ | The version identifyer of the new object | + + +__Example__ + + +```go +// Use-case 1: Simple copy object with no conditions. +// Source object +srcOpts := minio.CopySrcOptions{ + Bucket: "my-sourcebucketname", + Object: "my-sourceobjectname", +} + +// Destination object +dstOpts := minio.CopyDestOptions{ + Bucket: "my-bucketname", + Object: "my-objectname", +} + +// Copy object call +uploadInfo, err := minioClient.CopyObject(context.Background(), dst, src) +if err != nil { + fmt.Println(err) + return +} + +fmt.Println("Successfully copied object:", uploadInfo) +``` + +```go +// Use-case 2: +// Copy object with copy-conditions, and copying only part of the source object. +// 1. that matches a given ETag +// 2. and modified after 1st April 2014 +// 3. but unmodified since 23rd April 2014 +// 4. copy only first 1MiB of object. + +// Source object +srcOpts := minio.CopySrcOptions{ + Bucket: "my-sourcebucketname", + Object: "my-sourceobjectname", + MatchETag: "31624deb84149d2f8ef9c385918b653a", + MatchModifiedSince: time.Date(2014, time.April, 1, 0, 0, 0, 0, time.UTC), + MatchUnmodifiedSince: time.Date(2014, time.April, 23, 0, 0, 0, 0, time.UTC), + Start: 0, + End: 1024*1024-1, +} + + +// Destination object +dstOpts := minio.CopyDestOptions{ + Bucket: "my-bucketname", + Object: "my-objectname", +} + +// Copy object call +_, err = minioClient.CopyObject(context.Background(), dst, src) +if err != nil { + fmt.Println(err) + return +} + +fmt.Println("Successfully copied object:", uploadInfo) + +``` + + +### ComposeObject(ctx context.Context, dst minio.CopyDestOptions, srcs ...minio.CopySrcOptions) (UploadInfo, error) +Create an object by concatenating a list of source objects using server-side copying. + +__Parameters__ + + +| Param | Type | Description | +|:-------|:--------------------------|:----------------------------------------------------------------------------| +| `ctx` | _context.Context_ | Custom context for timeout/cancellation of the call | +| `dst` | _minio.CopyDestOptions_ | Struct with info about the object to be created. | +| `srcs` | _...minio.CopySrcOptions_ | Slice of struct with info about source objects to be concatenated in order. | + + +__minio.UploadInfo__ + +| Field | Type | Description | +|:--------------------|:---------|:-------------------------------------------| +| `info.ETag` | _string_ | The ETag of the new object | +| `info.VersionID` | _string_ | The version identifyer of the new object | + + +__Example__ + +```go +// Prepare source decryption key (here we assume same key to +// decrypt all source objects.) +sseSrc := encrypt.DefaultPBKDF([]byte("password"), []byte("salt")) + +// Source objects to concatenate. We also specify decryption +// key for each +src1Opts := minio.CopySrcOptions{ + Bucket: "bucket1", + Object: "object1", + Encryption: sseSrc, + MatchETag: "31624deb84149d2f8ef9c385918b653a", +} + +src2Opts := minio.CopySrcOptions{ + Bucket: "bucket2", + Object: "object2", + Encryption: sseSrc, + MatchETag: "f8ef9c385918b653a31624deb84149d2", +} + +src3Opts := minio.CopySrcOptions{ + Bucket: "bucket3", + Object: "object3", + Encryption: sseSrc, + MatchETag: "5918b653a31624deb84149d2f8ef9c38", +} + +// Prepare destination encryption key +sseDst := encrypt.DefaultPBKDF([]byte("new-password"), []byte("new-salt")) + +// Create destination info +dstOpts := CopyDestOptions{ + Bucket: "bucket", + Object: "object", + Encryption: sseDst, +} + +// Compose object call by concatenating multiple source files. +uploadInfo, err := minioClient.ComposeObject(context.Background(), dst, srcs...) +if err != nil { + fmt.Println(err) + return +} + +fmt.Println("Composed object successfully:", uploadInfo) +``` + + +### FPutObject(ctx context.Context, bucketName, objectName, filePath, opts PutObjectOptions) (info UploadInfo, err error) +Uploads contents from a file to objectName. + +FPutObject uploads objects that are less than 128MiB in a single PUT operation. For objects that are greater than the 128MiB in size, FPutObject seamlessly uploads the object in chunks of 128MiB or more depending on the actual file size. The max upload size for an object is 5TB. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`filePath` | _string_ |Path to file to be uploaded | +|`opts` | _minio.PutObjectOptions_ |Pointer to struct that allows user to set optional custom metadata, content-type, content-encoding, content-disposition, content-language and cache-control headers, pass encryption module for encrypting objects, and optionally configure number of threads for multipart put operation. | + + +__minio.UploadInfo__ + +| Field | Type | Description | +|:--------------------|:---------|:-------------------------------------------| +| `info.ETag` | _string_ | The ETag of the new object | +| `info.VersionID` | _string_ | The version identifyer of the new object | + + +__Example__ + + +```go +uploadInfo, err := minioClient.FPutObject(context.Background(), "my-bucketname", "my-objectname", "my-filename.csv", minio.PutObjectOptions{ + ContentType: "application/csv", +}); +if err != nil { + fmt.Println(err) + return +} +fmt.Println("Successfully uploaded object: ", uploadInfo) +``` + + +### StatObject(ctx context.Context, bucketName, objectName string, opts StatObjectOptions) (ObjectInfo, error) +Fetch metadata of an object. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`opts` | _minio.StatObjectOptions_ | Options for GET info/stat requests specifying additional options like encryption, If-Match | + + +__Return Value__ + +|Param |Type |Description | +|:---|:---| :---| +|`objInfo` | _minio.ObjectInfo_ |Object stat information | + + +__minio.ObjectInfo__ + +|Field |Type |Description | +|:---|:---| :---| +|`objInfo.LastModified` | _time.Time_ |Time when object was last modified | +|`objInfo.ETag` | _string_ |MD5 checksum of the object| +|`objInfo.ContentType` | _string_ |Content type of the object| +|`objInfo.Size` | _int64_ |Size of the object| + + +__Example__ + + +```go +objInfo, err := minioClient.StatObject(context.Background(), "mybucket", "myobject", minio.StatObjectOptions{}) +if err != nil { + fmt.Println(err) + return +} +fmt.Println(objInfo) +``` + + +### RemoveObject(ctx context.Context, bucketName, objectName string, opts minio.RemoveObjectOptions) error +Removes an object with some specified options + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`opts` |_minio.RemoveObjectOptions_ |Allows user to set options | + +__minio.RemoveObjectOptions__ + +|Field | Type | Description | +|:--- |:--- | :--- | +| `opts.GovernanceBypass` | _bool_ |Set the bypass governance header to delete an object locked with GOVERNANCE mode| +| `opts.VersionID` | _string_ |Version ID of the object to delete| +| `opts.Internal` | _minio.AdvancedRemoveOptions_ | This option is intended for internal use by MinIO server and should not be set unless the application is aware of intended use. + +```go +opts := minio.RemoveObjectOptions { + GovernanceBypass: true, + VersionID: "myversionid", + } +err = minioClient.RemoveObject(context.Background(), "mybucket", "myobject", opts) +if err != nil { + fmt.Println(err) + return +} +``` + +### PutObjectRetention(ctx context.Context, bucketName, objectName string, opts minio.PutObjectRetentionOptions) error +Applies object retention lock onto an object. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`opts` |_minio.PutObjectRetentionOptions_ |Allows user to set options like retention mode, expiry date and version id | + + +### RemoveObjects(ctx context.Context, bucketName string, objectsCh <-chan ObjectInfo, opts RemoveObjectsOptions) <-chan RemoveObjectError +Removes a list of objects obtained from an input channel. The call sends a delete request to the server up to 1000 objects at a time. The errors observed are sent over the error channel. + +Parameters + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectsCh` | _chan minio.ObjectInfo_ | Channel of objects to be removed | +|`opts` |_minio.RemoveObjectsOptions_ | Allows user to set options | + +__minio.RemoveObjectsOptions__ + +|Field | Type | Description | +|:--- |:--- | :--- | +| `opts.GovernanceBypass` | _bool_ |Set the bypass governance header to delete an object locked with GOVERNANCE mode| + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`errorCh` | _<-chan minio.RemoveObjectError_ | Receive-only channel of errors observed during deletion. | + +```go +objectsCh := make(chan minio.ObjectInfo) + +// Send object names that are needed to be removed to objectsCh +go func() { + defer close(objectsCh) + // List all objects from a bucket-name with a matching prefix. + for object := range minioClient.ListObjects(context.Background(), "my-bucketname", "my-prefixname", true, nil) { + if object.Err != nil { + log.Fatalln(object.Err) + } + objectsCh <- object + } +}() + +opts := minio.RemoveObjectsOptions{ + GovernanceBypass: true, +} + +for rErr := range minioClient.RemoveObjects(context.Background(), "my-bucketname", objectsCh, opts) { + fmt.Println("Error detected during deletion: ", rErr) +} +``` + + +### GetObjectRetention(ctx context.Context, bucketName, objectName, versionID string) (mode *RetentionMode, retainUntilDate *time.Time, err error) +Returns retention set on a given object. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`versionID` |_string_ |Version ID of the object | + +```go +err = minioClient.PutObjectRetention(context.Background(), "mybucket", "myobject", "") +if err != nil { + fmt.Println(err) + return +} +``` + +### PutObjectLegalHold(ctx context.Context, bucketName, objectName string, opts minio.PutObjectLegalHoldOptions) error +Applies legal-hold onto an object. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`opts` |_minio.PutObjectLegalHoldOptions_ |Allows user to set options like status and version id | + +_minio.PutObjectLegalHoldOptions_ + +|Field | Type | Description | +|:--- |:--- | :--- | +| `opts.Status` | _*minio.LegalHoldStatus_ |Legal-Hold status to be set| +| `opts.VersionID` | _string_ |Version ID of the object to apply retention on| + +```go +s := minio.LegalHoldEnabled +opts := minio.PutObjectLegalHoldOptions { + Status: &s, +} +err = minioClient.PutObjectLegalHold(context.Background(), "mybucket", "myobject", opts) +if err != nil { + fmt.Println(err) + return +} +``` + +### GetObjectLegalHold(ctx context.Context, bucketName, objectName, versionID string) (status *LegalHoldStatus, err error) +Returns legal-hold status on a given object. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`opts` |_minio.GetObjectLegalHoldOptions_ |Allows user to set options like version id | + +```go +opts := minio.GetObjectLegalHoldOptions{} +err = minioClient.GetObjectLegalHold(context.Background(), "mybucket", "myobject", opts) +if err != nil { + fmt.Println(err) + return +} +``` + +### SelectObjectContent(ctx context.Context, bucketName string, objectsName string, expression string, options SelectObjectOptions) *SelectResults +Parameters + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`ctx` | _context.Context_ |Request context | +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`options` | _SelectObjectOptions_ | Query Options | + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`SelectResults` | _SelectResults_ | Is an io.ReadCloser object which can be directly passed to csv.NewReader for processing output. | + +```go + // Initialize minio client object. + minioClient, err := minio.New(endpoint, &minio.Options{ + Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""), + Secure: useSSL, + }) + + opts := minio.SelectObjectOptions{ + Expression: "select count(*) from s3object", + ExpressionType: minio.QueryExpressionTypeSQL, + InputSerialization: minio.SelectObjectInputSerialization{ + CompressionType: minio.SelectCompressionNONE, + CSV: &minio.CSVInputOptions{ + FileHeaderInfo: minio.CSVFileHeaderInfoNone, + RecordDelimiter: "\n", + FieldDelimiter: ",", + }, + }, + OutputSerialization: minio.SelectObjectOutputSerialization{ + CSV: &minio.CSVOutputOptions{ + RecordDelimiter: "\n", + FieldDelimiter: ",", + }, + }, + } + + reader, err := s3Client.SelectObjectContent(context.Background(), "mycsvbucket", "mycsv.csv", opts) + if err != nil { + log.Fatalln(err) + } + defer reader.Close() + + if _, err := io.Copy(os.Stdout, reader); err != nil { + log.Fatalln(err) + } +``` + + +### PutObjectTagging(ctx context.Context, bucketName, objectName string, otags *tags.Tags) error +set new object Tags to the given object, replaces/overwrites any existing tags. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`objectTags` | _*tags.Tags_ | Map with Object Tag's Key and Value | + +__Example__ + + +```go +err = minioClient.PutObjectTagging(context.Background(), bucketName, objectName, objectTags) +if err != nil { + fmt.Println(err) + return +} +``` + + +### GetObjectTagging(ctx context.Context, bucketName, objectName string) (*tags.Tags, error) +Fetch Object Tags from the given object + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | + +__Example__ + + +```go +tags, err = minioClient.GetObjectTagging(context.Background(), bucketName, objectName) +if err != nil { + fmt.Println(err) + return +} +fmt.Printf("Fetched Tags: %s", tags) +``` + + +### RemoveObjectTagging(ctx context.Context, bucketName, objectName string) error +Remove Object Tags from the given object + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | + +__Example__ + + +```go +err = minioClient.RemoveObjectTagging(context.Background(), bucketName, objectName) +if err != nil { + fmt.Println(err) + return +} +``` + + +### RestoreObject(ctx context.Context, bucketName, objectName, versionID string, opts minio.RestoreRequest) error +Restore or perform SQL operations on an archived object + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`versionID` | _string_ |Version ID of the object | +|`opts` | _minio.RestoreRequest | Restore request options | + +__Example__ + +```go +opts := minio.RestoreRequest{} +opts.SetDays(1) +opts.SetGlacierJobParameters(minio.GlacierJobParameters{Tier: minio.TierStandard}) + +err = s3Client.RestoreObject(context.Background(), "your-bucket", "your-object", "", opts) +if err != nil { + log.Fatalln(err) +} +``` + + + +### RemoveIncompleteUpload(ctx context.Context, bucketName, objectName string) error +Removes a partially uploaded object. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | + +__Example__ + + +```go +err = minioClient.RemoveIncompleteUpload(context.Background(), "mybucket", "myobject") +if err != nil { + fmt.Println(err) + return +} +``` + +## 4. Presigned operations + + +### PresignedGetObject(ctx context.Context, bucketName, objectName string, expiry time.Duration, reqParams url.Values) (*url.URL, error) +Generates a presigned URL for HTTP GET operations. Browsers/Mobile clients may point to this URL to directly download objects even if the bucket is private. This presigned URL can have an associated expiration time in seconds after which it is no longer operational. The maximum expiry is 604800 seconds (i.e. 7 days) and minimum is 1 second. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`expiry` | _time.Duration_ |Expiry of presigned URL in seconds | +|`reqParams` | _url.Values_ |Additional response header overrides supports _response-expires_, _response-content-type_, _response-cache-control_, _response-content-disposition_. | + + +__Example__ + + +```go +// Set request parameters for content-disposition. +reqParams := make(url.Values) +reqParams.Set("response-content-disposition", "attachment; filename=\"your-filename.txt\"") + +// Generates a presigned url which expires in a day. +presignedURL, err := minioClient.PresignedGetObject(context.Background(), "mybucket", "myobject", time.Second * 24 * 60 * 60, reqParams) +if err != nil { + fmt.Println(err) + return +} +fmt.Println("Successfully generated presigned URL", presignedURL) +``` + + +### PresignedPutObject(ctx context.Context, bucketName, objectName string, expiry time.Duration) (*url.URL, error) +Generates a presigned URL for HTTP PUT operations. Browsers/Mobile clients may point to this URL to upload objects directly to a bucket even if it is private. This presigned URL can have an associated expiration time in seconds after which it is no longer operational. The default expiry is set to 7 days. + +NOTE: you can upload to S3 only with specified object name. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`expiry` | _time.Duration_ |Expiry of presigned URL in seconds | + + +__Example__ + + +```go +// Generates a url which expires in a day. +expiry := time.Second * 24 * 60 * 60 // 1 day. +presignedURL, err := minioClient.PresignedPutObject(context.Background(), "mybucket", "myobject", expiry) +if err != nil { + fmt.Println(err) + return +} +fmt.Println("Successfully generated presigned URL", presignedURL) +``` + + +### PresignedHeadObject(ctx context.Context, bucketName, objectName string, expiry time.Duration, reqParams url.Values) (*url.URL, error) +Generates a presigned URL for HTTP HEAD operations. Browsers/Mobile clients may point to this URL to directly get metadata from objects even if the bucket is private. This presigned URL can have an associated expiration time in seconds after which it is no longer operational. The default expiry is set to 7 days. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`objectName` | _string_ |Name of the object | +|`expiry` | _time.Duration_ |Expiry of presigned URL in seconds | +|`reqParams` | _url.Values_ |Additional response header overrides supports _response-expires_, _response-content-type_, _response-cache-control_, _response-content-disposition_. | + + +__Example__ + + +```go +// Set request parameters for content-disposition. +reqParams := make(url.Values) +reqParams.Set("response-content-disposition", "attachment; filename=\"your-filename.txt\"") + +// Generates a presigned url which expires in a day. +presignedURL, err := minioClient.PresignedHeadObject(context.Background(), "mybucket", "myobject", time.Second * 24 * 60 * 60, reqParams) +if err != nil { + fmt.Println(err) + return +} +fmt.Println("Successfully generated presigned URL", presignedURL) +``` + + +### PresignedPostPolicy(ctx context.Context, post PostPolicy) (*url.URL, map[string]string, error) +Allows setting policy conditions to a presigned URL for POST operations. Policies such as bucket name to receive object uploads, key name prefixes, expiry policy may be set. + +```go +// Initialize policy condition config. +policy := minio.NewPostPolicy() + +// Apply upload policy restrictions: +policy.SetBucket("mybucket") +policy.SetKey("myobject") +policy.SetExpires(time.Now().UTC().AddDate(0, 0, 10)) // expires in 10 days + +// Only allow 'png' images. +policy.SetContentType("image/png") + +// Only allow content size in range 1KB to 1MB. +policy.SetContentLengthRange(1024, 1024*1024) + +// Add a user metadata using the key "custom" and value "user" +policy.SetUserMetadata("custom", "user") + +// Get the POST form key/value object: +url, formData, err := minioClient.PresignedPostPolicy(context.Background(), policy) +if err != nil { + fmt.Println(err) + return +} + +// POST your content from the command line using `curl` +fmt.Printf("curl ") +for k, v := range formData { + fmt.Printf("-F %s=%s ", k, v) +} +fmt.Printf("-F file=@/etc/bash.bashrc ") +fmt.Printf("%s\n", url) +``` + +## 5. Bucket policy/notification operations + + +### SetBucketPolicy(ctx context.Context, bucketname, policy string) error +Set access permissions on bucket or an object prefix. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket| +|`policy` | _string_ |Policy to be set | + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +policy := `{"Version": "2012-10-17","Statement": [{"Action": ["s3:GetObject"],"Effect": "Allow","Principal": {"AWS": ["*"]},"Resource": ["arn:aws:s3:::my-bucketname/*"],"Sid": ""}]}` + +err = minioClient.SetBucketPolicy(context.Background(), "my-bucketname", policy) +if err != nil { + fmt.Println(err) + return +} +``` + + +### GetBucketPolicy(ctx context.Context, bucketName string) (policy string, error) +Get access permissions on a bucket or a prefix. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`policy` | _string_ |Policy returned from the server | +|`err` | _error_ |Standard Error | + +__Example__ + +```go +policy, err := minioClient.GetBucketPolicy(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +``` + + +### GetBucketNotification(ctx context.Context, bucketName string) (notification.Configuration, error) +Get notification configuration on a bucket. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`config` | _notification.Configuration_ |structure which holds all notification configurations| +|`err` | _error_ |Standard Error | + +__Example__ + + +```go +bucketNotification, err := minioClient.GetBucketNotification(context.Background(), "mybucket") +if err != nil { + fmt.Println("Failed to get bucket notification configurations for mybucket", err) + return +} + +for _, queueConfig := range bucketNotification.QueueConfigs { + for _, e := range queueConfig.Events { + fmt.Println(e + " event is enabled") + } +} +``` + + +### SetBucketNotification(ctx context.Context, bucketName string, config notification.Configuration) error +Set a new bucket notification on a bucket. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | +|`config` | _notification.Configuration_ |Represents the XML to be sent to the configured web service | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + + +```go +queueArn := notification.NewArn("aws", "sqs", "us-east-1", "804605494417", "PhotoUpdate") + +queueConfig := notification.NewConfig(queueArn) +queueConfig.AddEvents(minio.ObjectCreatedAll, minio.ObjectRemovedAll) +queueConfig.AddFilterPrefix("photos/") +queueConfig.AddFilterSuffix(".jpg") + +config := notification.Configuration{} +config.AddQueue(queueConfig) + +err = minioClient.SetBucketNotification(context.Background(), "mybucket", config) +if err != nil { + fmt.Println("Unable to set the bucket notification: ", err) + return +} +``` + + +### RemoveAllBucketNotification(ctx context.Context, bucketName string) error +Remove all configured bucket notifications on a bucket. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + + +```go +err = minioClient.RemoveAllBucketNotification(context.Background(), "mybucket") +if err != nil { + fmt.Println("Unable to remove bucket notifications.", err) + return +} +``` + + +### ListenBucketNotification(context context.Context, bucketName, prefix, suffix string, events []string) <-chan notification.Info +ListenBucketNotification API receives bucket notification events through the notification channel. The returned notification channel has two fields 'Records' and 'Err'. + +- 'Records' holds the notifications received from the server. +- 'Err' indicates any error while processing the received notifications. + +NOTE: Notification channel is closed at the first occurrence of an error. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`bucketName` | _string_ | Bucket to listen notifications on | +|`prefix` | _string_ | Object key prefix to filter notifications for | +|`suffix` | _string_ | Object key suffix to filter notifications for | +|`events` | _[]string_ | Enables notifications for specific event types | + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`notificationInfo` | _chan notification.Info_ | Channel of bucket notifications | + +__minio.NotificationInfo__ + +|Field |Type |Description | +|`notificationInfo.Records` | _[]notification.Event_ | Collection of notification events | +|`notificationInfo.Err` | _error_ | Carries any error occurred during the operation (Standard Error) | + + +__Example__ + + +```go +// Listen for bucket notifications on "mybucket" filtered by prefix, suffix and events. +for notificationInfo := range minioClient.ListenBucketNotification(context.Background(), "mybucket", "myprefix/", ".mysuffix", []string{ + "s3:ObjectCreated:*", + "s3:ObjectAccessed:*", + "s3:ObjectRemoved:*", + }) { + if notificationInfo.Err != nil { + fmt.Println(notificationInfo.Err) + } + fmt.Println(notificationInfo) +} +``` + + +### ListenNotification(context context.Context, prefix, suffix string, events []string) <-chan notification.Info +ListenNotification API receives bucket and object notification events through the notification channel. The returned notification channel has two fields 'Records' and 'Err'. + +- 'Records' holds the notifications received from the server. +- 'Err' indicates any error while processing the received notifications. + +NOTE: Notification channel is closed at the first occurrence of an error. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`bucketName` | _string_ | Bucket to listen notifications on | +|`prefix` | _string_ | Object key prefix to filter notifications for | +|`suffix` | _string_ | Object key suffix to filter notifications for | +|`events` | _[]string_ | Enables notifications for specific event types | + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`notificationInfo` | _chan notification.Info_ | Read channel for all notifications | + +__minio.NotificationInfo__ + +|Field |Type |Description | +|`notificationInfo.Records` | _[]notification.Event_ | Collection of notification events | +|`notificationInfo.Err` | _error_ | Carries any error occurred during the operation (Standard Error) | + +__Example__ + + +```go +// Listen for bucket notifications on "mybucket" filtered by prefix, suffix and events. +for notificationInfo := range minioClient.ListenNotification(context.Background(), "myprefix/", ".mysuffix", []string{ + "s3:BucketCreated:*", + "s3:BucketRemoved:*", + "s3:ObjectCreated:*", + "s3:ObjectAccessed:*", + "s3:ObjectRemoved:*", + }) { + if notificationInfo.Err != nil { + fmt.Println(notificationInfo.Err) + } + fmt.Println(notificationInfo) +} +``` + + +### SetBucketLifecycle(ctx context.Context, bucketname, config *lifecycle.Configuration) error +Set lifecycle on bucket or an object prefix. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket| +|`config` | _lifecycle.Configuration_ |Lifecycle to be set | + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +config := lifecycle.NewConfiguration() +config.Rules = []lifecycle.Rule{ + { + ID: "expire-bucket", + Status: "Enabled", + Expiration: lifecycle.Expiration{ + Days: 365, + }, + }, +} + +err = minioClient.SetBucketLifecycle(context.Background(), "my-bucketname", config) +if err != nil { + fmt.Println(err) + return +} +``` + + +### GetBucketLifecycle(ctx context.Context, bucketName string) (*lifecycle.Configuration error) +Get lifecycle on a bucket or a prefix. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`config` | _lifecycle.Configuration_ |Lifecycle returned from the server | +|`err` | _error_ |Standard Error | + +__Example__ + +```go +lifecycle, err := minioClient.GetBucketLifecycle(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +``` + + +### SetBucketEncryption(ctx context.Context, bucketname string, config sse.Configuration) error +Set default encryption configuration on a bucket. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket| +|`config` | _sse.Configuration_ | Structure that holds default encryption configuration to be set | + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +s3Client, err := minio.New("s3.amazonaws.com", &minio.Options{ + Creds: credentials.NewStaticV4("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""), + Secure: true, +}) +if err != nil { + log.Fatalln(err) +} + +// Set default encryption configuration on an S3 bucket +err = s3Client.SetBucketEncryption(context.Background(), "my-bucketname", sse.NewConfigurationSSES3()) +if err != nil { + log.Fatalln(err) +} +``` + + +### GetBucketEncryption(ctx context.Context, bucketName string) (*sse.Configuration, error) +Get default encryption configuration set on a bucket. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`config` | _sse.Configuration_ | Structure that holds default encryption configuration | +|`err` | _error_ |Standard Error | + +__Example__ + +```go +s3Client, err := minio.New("s3.amazonaws.com", &minio.Options{ + Creds: credentials.NewStaticV4("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""), + Secure: true, +}) +if err != nil { + log.Fatalln(err) +} + +// Get default encryption configuration set on an S3 bucket and print it out +encryptionConfig, err := s3Client.GetBucketEncryption(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +fmt.Printf("%+v\n", encryptionConfig) +``` + + +### RemoveBucketEncryption(ctx context.Context, bucketName string) (error) +Remove default encryption configuration set on a bucket. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---|:---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +err := s3Client.RemoveBucketEncryption(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +// "my-bucket" is successfully deleted/removed. +``` + + +### SetObjectLockConfig(ctx context.Context, bucketname, mode *RetentionMode, validity *uint, unit *ValidityUnit) error +Set object lock configuration in given bucket. mode, validity and unit are either all set or all nil. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket| +|`mode` | _RetentionMode_ |Retention mode to be set | +|`validity` | _uint_ |Validity period to be set | +|`unit` | _ValidityUnit_ |Unit of validity period | + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +mode := Governance +validity := uint(30) +unit := Days + +err = minioClient.SetObjectLockConfig(context.Background(), "my-bucketname", &mode, &validity, &unit) +if err != nil { + fmt.Println(err) + return +} +``` + + +### GetObjectLockConfig(ctx context.Context, bucketName string) (objectLock,*RetentionMode, *uint, *ValidityUnit, error) +Get object lock configuration of given bucket. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`objectLock` | _objectLock_ |lock enabled status | +|`mode` | _RetentionMode_ |Current retention mode | +|`validity` | _uint_ |Current validity period | +|`unit` | _ValidityUnit_ |Unit of validity period | +|`err` | _error_ |Standard Error | + +__Example__ + +```go +enabled, mode, validity, unit, err := minioClient.GetObjectLockConfig(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +fmt.Println("object lock is %s for this bucket",enabled) +if mode != nil { + fmt.Printf("%v mode is enabled for %v %v for bucket 'my-bucketname'\n", *mode, *validity, *unit) +} else { + fmt.Println("No mode is enabled for bucket 'my-bucketname'") +} +``` + + +### EnableVersioning(ctx context.Context, bucketName string) error +Enable bucket versioning support. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +err := minioClient.EnableVersioning(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} + +fmt.Println("versioning enabled for bucket 'my-bucketname'") +``` + + +### DisableVersioning(ctx context.Context, bucketName) error +Disable bucket versioning support. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +err := minioClient.DisableVersioning(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} + +fmt.Println("versioning disabled for bucket 'my-bucketname'") +``` + + +### GetBucketVersioning(ctx context.Context, bucketName string) (BucketVersioningConfiguration, error) +Get versioning configuration set on a bucket. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`configuration` | _minio.BucketVersioningConfiguration_ | Structure that holds versioning configuration | +|`err` | _error_ |Standard Error | + +__Example__ + +```go +s3Client, err := minio.New("s3.amazonaws.com", &minio.Options{ + Creds: credentials.NewStaticV4("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""), + Secure: true, +}) +if err != nil { + log.Fatalln(err) +} + +// Get versioning configuration set on an S3 bucket and print it out +versioningConfig, err := s3Client.GetBucketVersioning(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +fmt.Printf("%+v\n", versioningConfig) +``` + + + +### SetBucketReplication(ctx context.Context, bucketname, cfg replication.Config) error +Set replication configuration on a bucket. Role can be obtained by first defining the replication target on MinIO using `mc admin bucket remote set` to associate the source and destination buckets for replication with the replication endpoint. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket| +|`cfg` | _replication.Config_ |Replication configuration to be set | + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +replicationStr := ` + + + + Disabled + + + string + string + + + + string + + string + string + + ... + + string + + string + string + + + string + string + integer + string + +` +replicationConfig := replication.Config{} +if err := xml.Unmarshal([]byte(replicationStr), &replicationConfig); err != nil { + log.Fatalln(err) +} +cfg.Role := "arn:minio:s3::598361bf-3cec-49a7-b529-ce870a34d759:*" +err = minioClient.SetBucketReplication(context.Background(), "my-bucketname", replicationConfig) +if err != nil { + fmt.Println(err) + return +} +``` + + +### GetBucketReplication(ctx context.Context, bucketName string) (replication.Config, error) +Get current replication config on a bucket. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`replication` | _replication.Config_ |Replication config returned from the server | +|`err` | _error_ |Standard Error | + +__Example__ + +```go +replication, err := minioClient.GetBucketReplication(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +``` + + +### RemoveBucketReplication(ctx context.Context, bucketname string) error +Removes replication configuration on a bucket. + +__Parameters__ + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket| + +__Return Values__ + +|Param |Type |Description | +|:---|:---| :---| +|`err` | _error_ |Standard Error | + +__Example__ + +```go +err = minioClient.RemoveBucketReplication(context.Background(), "my-bucketname") +if err != nil { + fmt.Println(err) + return +} +``` + + +### GetBucketReplicationMetrics(ctx context.Context, bucketName string) (replication.Metrics, error) +Get latest replication metrics on a bucket. This is a MinIO specific extension. + +__Parameters__ + + +|Param |Type |Description | +|:---|:---| :---| +|`ctx` | _context.Context_ | Custom context for timeout/cancellation of the call| +|`bucketName` | _string_ |Name of the bucket | + +__Return Values__ + + +|Param |Type |Description | +|:---|:---| :---| +|`metrics` | _replication.Metrics_ |Replication metrics returned from the server | +|`err` | _error_ |Standard Error | + +__Example__ + +```go +replMetrics, err := minioClient.GetBucketReplicationMetrics(context.Background(), "my-bucketname") +if err != nil { + log.Fatalln(err) +} +``` + +## 6. Client custom settings + + +### SetAppInfo(appName, appVersion string) +Add custom application details to User-Agent. + +__Parameters__ + +| Param | Type | Description | +|---|---|---| +|`appName` | _string_ | Name of the application performing the API requests. | +| `appVersion`| _string_ | Version of the application performing the API requests. | + + +__Example__ + + +```go +// Set Application name and version to be used in subsequent API requests. +minioClient.SetAppInfo("myCloudApp", "1.0.0") +``` + + +### TraceOn(outputStream io.Writer) +Enables HTTP tracing. The trace is written to the io.Writer provided. If outputStream is nil, trace is written to os.Stdout. + +__Parameters__ + +| Param | Type | Description | +|---|---|---| +|`outputStream` | _io.Writer_ | HTTP trace is written into outputStream.| + + + +### TraceOff() +Disables HTTP tracing. + + +### SetS3TransferAccelerate(acceleratedEndpoint string) +Set AWS S3 transfer acceleration endpoint for all API requests hereafter. +NOTE: This API applies only to AWS S3 and is a no operation for S3 compatible object storage services. + +__Parameters__ + +| Param | Type | Description | +|---|---|---| +|`acceleratedEndpoint` | _string_ | Set to new S3 transfer acceleration endpoint.| diff --git a/source/sdk/go/minio-go.rst b/source/sdk/go/minio-go.rst new file mode 100644 index 00000000..4bd17b43 --- /dev/null +++ b/source/sdk/go/minio-go.rst @@ -0,0 +1,10 @@ +.. _minio-go: + +.. default-domain:: minio + +.. contents:: Table of Contents + :local: + :depth: 2 + +.. include:: /sdk/go/API.md + :parser: myst_parser.sphinx_ diff --git a/source/sdk/java/API.md b/source/sdk/java/API.md new file mode 100644 index 00000000..ea13fd9e --- /dev/null +++ b/source/sdk/java/API.md @@ -0,0 +1,1873 @@ +# Java Client API Reference [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +## Create MinIO Client. + +## MinIO + +```java +MinioClient minioClient = + MinioClient.builder() + .endpoint("https://play.min.io") + .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + .build(); +``` + +## AWS S3 + +```java +MinioClient minioClient = + MinioClient.builder() + .endpoint("https://s3.amazonaws.com") + .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY") + .build(); +``` + +| Bucket operations | Object operations | +|-------------------------------------------------------------------|---------------------------------------------------------| +| [`bucketExists`](#bucketExists) | [`composeObject`](#composeObject) | +| [`deleteBucketEncryption`](#deleteBucketEncryption) | [`copyObject`](#copyObject) | +| [`deleteBucketLifecycle`](#deleteBucketLifecycle) | [`deleteObjectTags`](#deleteObjectTags) | +| [`deleteBucketNotification`](#deleteBucketNotification) | [`disableObjectLegalHold`](#disableObjectLegalHold) | +| [`deleteBucketPolicy`](#deleteBucketPolicy) | [`downloadObject`](#downloadObject) | +| [`deleteBucketReplication`](#deleteBucketReplication) | [`enableObjectLegalHold`](#enableObjectLegalHold) | +| [`deleteBucketTags`](#deleteBucketTags) | [`getObject`](#getObject) | +| [`deleteObjectLockConfiguration`](#deleteObjectLockConfiguration) | [`getObjectRetention`](#getObjectRetention) | +| [`getBucketEncryption`](#getBucketEncryption) | [`getObjectTags`](#getObjectTags) | +| [`getBucketLifecycle`](#getBucketLifecycle) | [`getPresignedObjectUrl`](#getPresignedObjectUrl) | +| [`getBucketNotification`](#getBucketNotification) | [`getPresignedPostFormData`](#getPresignedPostFormData) | +| [`getBucketPolicy`](#getBucketPolicy) | [`isObjectLegalHoldEnabled`](#isObjectLegalHoldEnabled) | +| [`getBucketReplication`](#getBucketReplication) | [`listObjects`](#listObjects) | +| [`getBucketTags`](#getBucketTags) | [`putObject`](#putObject) | +| [`getBucketVersioning`](#getBucketVersioning) | [`removeObject`](#removeObject) | +| [`getObjectLockConfiguration`](#getObjectLockConfiguration) | [`removeObjects`](#removeObjects) | +| [`listBuckets`](#listBuckets) | [`selectObjectContent`](#selectObjectContent) | +| [`listenBucketNotification`](#listenBucketNotification) | [`setObjectRetention`](#setObjectRetention) | +| [`makeBucket`](#makeBucket) | [`setObjectTags`](#setObjectTags) | +| [`removeBucket`](#removeBucket) | [`statObject`](#statObject) | +| [`setBucketEncryption`](#setBucketEncryption) | [`uploadObject`](#uploadObject) | +| [`setBucketLifecycle`](#setBucketLifecycle) | [`uploadSnowballObjects`](#uploadSnowballObjects) | +| [`setBucketNotification`](#setBucketNotification) | | +| [`setBucketPolicy`](#setBucketPolicy) | | +| [`setBucketReplication`](#setBucketReplication) | | +| [`setBucketTags`](#setBucketTags) | | +| [`setBucketVersioning`](#setBucketVersioning) | | +| [`setObjectLockConfiguration`](#setObjectLockConfiguration) | | + +## 1. MinIO Client Builder + +MinIO Client Builder is used to create MinIO client. Builder has below methods to accept arguments. +| Method | Description | +|-----------------|--------------------------------------------------------------------------------------------------------------------------------------------| +| `endpoint()` | Accepts endpoint as a String, URL or okhttp3.HttpUrl object and optionally accepts port number and flag to enable secure (TLS) connection. | +| | Endpoint as a string can be formatted like below: | +| | `https://s3.amazonaws.com` | +| | `https://play.min.io` | +| | `https://play.min.io:9000` | +| | `localhost` | +| | `play.min.io` | +| `credentials()` | Accepts access key (aka user ID) and secret key (aka password) of an account in S3 service. | +| `region()` | Accepts region name of S3 service. If specified, all operations use this region otherwise region is probed per bucket. | +| `httpClient()` | Custom HTTP client to override default. | + +__Examples__ + +### MinIO + +```java +// 1. Create client to S3 service 'play.min.io' at port 443 with TLS security +// for anonymous access. +MinioClient minioClient = MinioClient.builder().endpoint("https://play.min.io").build(); + +// 2. Create client to S3 service 'play.min.io' at port 443 with TLS security +// using URL object for anonymous access. +MinioClient minioClient = MinioClient.builder().endpoint(new URL("https://play.min.io")).build(); + +// 3. Create client to S3 service 'play.min.io' at port 9000 with TLS security +// using okhttp3.HttpUrl object for anonymous access. +MinioClient minioClient = + MinioClient.builder().endpoint(HttpUrl.parse("https://play.min.io:9000")).build(); + +// 4. Create client to S3 service 'play.min.io' at port 443 with TLS security +// for authenticated access. +MinioClient minioClient = + MinioClient.builder() + .endpoint("https://play.min.io") + .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + .build(); + +// 5. Create client to S3 service 'play.min.io' at port 9000 with non-TLS security +// for authenticated access. +MinioClient minioClient = + MinioClient.builder() + .endpoint("play.min.io", 9000, false) + .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + .build(); + +// 6. Create client to S3 service 'play.min.io' at port 9000 with TLS security +// for authenticated access. +MinioClient minioClient = + MinioClient.builder() + .endpoint("play.min.io", 9000, true) + .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + .build(); + +// 7. Create client to S3 service 'play.min.io' at port 443 with TLS security +// and region 'us-west-1' for authenticated access. +MinioClient minioClient = + MinioClient.builder() + .endpoint(new URL("https://play.min.io")) + .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + .region("us-west-1") + .build(); + +// 8. Create client to S3 service 'play.min.io' at port 9000 with TLS security, +// region 'eu-east-1' and custom HTTP client for authenticated access. +MinioClient minioClient = + MinioClient.builder() + .endpoint("https://play.min.io:9000") + .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG") + .region("eu-east-1") + .httpClient(customHttpClient) + .build(); +``` + +### AWS S3 + +```java +// 1. Create client to S3 service 's3.amazonaws.com' at port 443 with TLS security +// for anonymous access. +MinioClient s3Client = MinioClient.builder().endpoint("https://s3.amazonaws.com").build(); + +// 2. Create client to S3 service 's3.amazonaws.com' at port 443 with TLS security +// using URL object for anonymous access. +MinioClient s3Client = MinioClient.builder().endpoint(new URL("https://s3.amazonaws.com")).build(); + +// 3. Create client to S3 service 's3.amazonaws.com' at port 9000 with TLS security +// using okhttp3.HttpUrl object for anonymous access. +MinioClient s3Client = + MinioClient.builder().endpoint(HttpUrl.parse("https://s3.amazonaws.com")).build(); + +// 4. Create client to S3 service 's3.amazonaws.com' at port 80 with TLS security +// for authenticated access. +MinioClient s3Client = + MinioClient.builder() + .endpoint("s3.amazonaws.com") + .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY") + .build(); + +// 5. Create client to S3 service 's3.amazonaws.com' at port 443 with non-TLS security +// for authenticated access. +MinioClient s3Client = + MinioClient.builder() + .endpoint("s3.amazonaws.com", 433, false) + .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY") + .build(); + +// 6. Create client to S3 service 's3.amazonaws.com' at port 80 with non-TLS security +// for authenticated access. +MinioClient s3Client = + MinioClient.builder() + .endpoint("s3.amazonaws.com", 80, false) + .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY") + .build(); + +// 7. Create client to S3 service 's3.amazonaws.com' at port 80 with TLS security +// for authenticated access. +MinioClient s3Client = + MinioClient.builder() + .endpoint("s3.amazonaws.com", 80, true) + .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY") + .build(); + +// 8. Create client to S3 service 's3.amazonaws.com' at port 80 with non-TLS security +// and region 'us-west-1' for authenticated access. +MinioClient s3Client = + MinioClient.builder() + .endpoint("s3.amazonaws.com", 80, false) + .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY") + .region("us-west-1") + .build(); + +// 9. Create client to S3 service 's3.amazonaws.com' at port 443 with TLS security +// and region 'eu-west-2' for authenticated access. +MinioClient s3Client = + MinioClient.builder() + .endpoint("s3.amazonaws.com", 443, true) + .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY"). + .region("eu-west-2") + .build(); + +// 10. Create client to S3 service 's3.amazonaws.com' at port 443 with TLS security, +// region 'eu-central-1' and custom HTTP client for authenticated access. +MinioClient s3Client = + MinioClient.builder() + .endpoint("s3.amazonaws.com", 443, true) + .credentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY") + .region("eu-central-1") + .httpClient(customHttpClient) + .build(); +``` + +## Common Exceptions +All APIs throw below exceptions in addition to specific to API. + +| Exception | Cause | +|:--------------------------|:---------------------------------------------------------------------| +| ErrorResponseException | Thrown to indicate S3 service returned an error response. | +| IllegalArgumentException | Throws to indicate invalid argument passed. | +| InsufficientDataException | Thrown to indicate not enough data available in InputStream. | +| InternalException | Thrown to indicate internal library error. | +| InvalidKeyException | Thrown to indicate missing of HMAC SHA-256 library. | +| InvalidResponseException | Thrown to indicate S3 service returned invalid or no error response. | +| IOException | Thrown to indicate I/O error on S3 operation. | +| NoSuchAlgorithmException | Thrown to indicate missing of MD5 or SHA-256 digest library. | +| ServerException | Thrown to indicate HTTP server error. | +| XmlParserException | Thrown to indicate XML parsing error. | + +## 2. Bucket operations + + +### bucketExists(BucketExistsArgs args) +`public boolean bucketExists(BucketExistsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#bucketExists-io.minio.BucketExistsArgs-)_ + +Checks if a bucket exists. + +__Parameters__ +| Parameter | Type | Description | +|:---------------|:---------------------|:---------------| +| ``bucketName`` | _[BucketExistsArgs]_ | Arguments. | + +| Returns | +|:---------------------------------------| +| _boolean_ - True if the bucket exists. | + +__Example__ +```java +// Check whether 'my-bucketname' exists or not. +boolean found = + minioClient.bucketExists(BucketExistsArgs.builder().bucket("my-bucketname").build()); +if (found) { + System.out.println("my-bucketname exists"); +} else { + System.out.println("my-bucketname does not exist"); +} +``` + + +### deleteBucketEncryption(DeleteBucketEncryptionArgs args) +`private void deleteBucketEncryption(DeleteBucketEncryptionArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#deleteBucketEncryption-io.minio.DeleteBucketEncryptionArgs-)_ + +Deletes encryption configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:-------------------------------|:------------| +| ``args`` | _[DeleteBucketEncryptionArgs]_ | Arguments. | + +__Example__ +```java +minioClient.deleteBucketEncryption( + DeleteBucketEncryptionArgs.builder().bucket("my-bucketname").build()); +``` + + +### deleteBucketLifecycle(DeleteBucketLifecycleArgs args) +`private void deleteBucketLifecycle(DeleteBucketLifecycleArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#deleteBucketLifecycle-io.minio.DeleteBucketLifecycleArgs-)_ + +Deletes lifecycle configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:------------------------------|:------------| +| ``args`` | _[DeleteBucketLifecycleArgs]_ | Arguments. | + +__Example__ +```java +minioClient.deleteBucketLifecycle( + DeleteBucketLifecycleArgs.builder().bucket("my-bucketname").build()); +``` + + +### deleteBucketTags(DeleteBucketTagsArgs args) +`private void deleteBucketTags(DeleteBucketTagsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#deleteBucketTags-io.minio.DeleteBucketTagsArgs-)_ + +Deletes tags of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:-------------------------|:------------| +| ``args`` | _[DeleteBucketTagsArgs]_ | Arguments. | + +__Example__ +```java +minioClient.deleteBucketTags(DeleteBucketTagsArgs.builder().bucket("my-bucketname").build()); +``` + + +### deleteBucketPolicy(DeleteBucketPolicyArgs args) +`private void deleteBucketPolicy(DeleteBucketPolicyArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#deleteBucketPolicy-io.minio.DeleteBucketPolicyArgs-)_ + +Deletes bucket policy configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:---------------------------|:------------| +| ``args`` | _[DeleteBucketPolicyArgs]_ | Arguments. | + +__Example__ +```java +minioClient.deleteBucketPolicy(DeleteBucketPolicyArgs.builder().bucket("my-bucketname").build()); +``` + + +### deleteBucketReplication(DeleteBucketReplicationArgs args) +`private void deleteBucketReplication(DeleteBucketReplicationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#deleteBucketReplication-io.minio.DeleteBucketReplicationArgs-)_ + +Deletes bucket replication configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:--------------------------------|:------------| +| ``args`` | _[DeleteBucketReplicationArgs]_ | Arguments. | + +__Example__ +```java +minioClient.deleteBucketReplication( + DeleteBucketReplicationArgs.builder().bucket("my-bucketname").build()); +``` + + +### deleteBucketNotification(DeleteBucketNotificationArgs args) +`public void deleteBucketNotification(DeleteBucketNotificationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#deleteBucketNotification-io.minio.DeleteBucketNotificationArgs-)_ + +Deletes notification configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:---------------------------------|:------------| +| ``args`` | _[DeleteBucketNotificationArgs]_ | Arguments. | + +__Example__ +```java +minioClient.deleteBucketNotification( + DeleteBucketNotificationArgs.builder().bucket("my-bucketname").build()); +``` + + +### deleteObjectLockConfiguration(DeleteObjectLockConfigurationArgs args) +`public void deleteObjectLockConfiguration(DeleteObjectLockConfigurationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#deleteObjectLockConfiguration-io.minio.DeleteObjectLockConfigurationArgs-)_ + +Deletes object-lock configuration in a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:--------------------------------------|:------------| +| ``args`` | _[DeleteObjectLockConfigurationArgs]_ | Arguments. | + +__Example__ +```java +minioClient.deleteObjectLockConfiguration( + DeleteObjectLockConfigurationArgs.builder().bucket("my-bucketname").build()); +``` + + +### getBucketEncryption(GetBucketEncryptionArgs args) +`public SseConfiguration getBucketEncryption(GetBucketEncryptionArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getBucketEncryption-io.minio.GetBucketEncryptionArgs-)_ + +Gets encryption configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:----------------------------|:------------| +| ``args`` | _[GetBucketEncryptionArgs]_ | Arguments. | + +| Returns | +|:-------------------------------------------------------------| +| _[SseConfiguration]_ - Server-side encryption configuration. | + +__Example__ +```java +SseConfiguration config = + minioClient.getBucketEncryption( + GetBucketEncryptionArgs.builder().bucket("my-bucketname").build()); +``` + + +### getBucketLifecycle(GetBucketLifecycleArgs args) +`public LifecycleConfiguration getBucketLifecycle(GetBucketLifecycleArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getBucketLifecycle-io.minio.GetBucketLifecycleArgs-)_ + +Gets lifecycle configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:---------------------------|:------------| +| ``args`` | _[GetBucketLifecycleArgs]_ | Arguments. | + +| Returns | +|:------------------------------------------------------| +| _[LifecycleConfiguration]_ - lifecycle configuration. | + +__Example__ +```java +LifecycleConfiguration config = + minioClient.getBucketLifecycle( + GetBucketLifecycleArgs.builder().bucket("my-bucketname").build()); +System.out.println("Lifecycle configuration: " + config); +``` + + +### getBucketNotification(GetBucketNotificationArgs args) +`public NotificationConfiguration getBucketNotification(GetBucketNotificationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getBucketNotification-io.minio.GetBucketNotificationArgs-)_ + +Gets notification configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:------------------------------|:------------| +| ``args`` | _[GetBucketNotificationArgs]_ | Arguments. | + +| Returns | +|:------------------------------------------------------------| +| _[NotificationConfiguration]_ - Notification configuration. | + +__Example__ +```java +NotificationConfiguration config = + minioClient.getBucketNotification( + GetBucketNotificationArgs.builder().bucket("my-bucketname").build()); +``` + + +### getBucketPolicy(GetBucketPolicyArgs args) +`public String getBucketPolicy(GetBucketPolicyArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getBucketPolicy-io.minio.GetBucketPolicyArgs-)_ + +Gets bucket policy configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:------------------------|:------------| +| ``args`` | _[GetBucketPolicyArgs]_ | Arguments. | + + +| Returns | +|:-------------------------------------------------------| +| _String_ - Bucket policy configuration as JSON string. | + +__Example__ +```java +String config = + minioClient.getBucketPolicy(GetBucketPolicyArgs.builder().bucket("my-bucketname").build()); +``` + + +### getBucketReplication(GetBucketReplicationArgs args) +`public ReplicationConfiguration getBucketReplication(GetBucketReplicationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getBucketReplication-io.minio.GetBucketReplicationArgs-)_ + +Gets bucket replication configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:-----------------------------|:------------| +| ``args`` | _[GetBucketReplicationArgs]_ | Arguments. | + + +| Returns | +|:-----------------------------------------------------------------| +| _[ReplicationConfiguration]_ - Bucket replication configuration. | + +__Example__ +```java +ReplicationConfiguration config = + minioClient.getBucketReplication( + GetBucketReplicationArgs.builder().bucket("my-bucketname").build()); +``` + + +### getBucketTags(GetBucketTagsArgs args) +`public Tags getBucketTags(GetBucketTagsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.htmlgetBucketTags-io.minio.GetBucketTagsArgs-)_ + +Gets tags of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:----------------------|:------------| +| ``args`` | _[GetBucketTagsArgs]_ | Arguments. | + + +| Returns | +|:-----------------| +| _[Tags]_ - tags. | + +__Example__ +```java +Tags tags = minioClient.getBucketTags(GetBucketTagsArgs.builder().bucket("my-bucketname").build()); +``` + + +### getBucketVersioning(GetBucketVersioningArgs args) +`public VersioningConfiguration getBucketVersioning(GetBucketVersioningArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getBucketVersioning-io.minio.GetBucketVersioningArgs-)_ + +Gets versioning configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:----------------------------|:------------| +| ``args`` | _[GetBucketVersioningArgs]_ | Arguments. | + +| Returns | +|:--------------------------------------------------------| +| _[VersioningConfiguration]_ - Versioning configuration. | + +__Example__ +```java +VersioningConfiguration config = + minioClient.getBucketVersioning( + GetBucketVersioningArgs.builder().bucket("my-bucketname").build()); +``` + + +### getObjectLockConfiguration(GetObjectLockConfigurationArgs args) +`public ObjectLockConfiguration getObjectLockConfiguration(GetObjectLockConfigurationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getObjectLockConfiguration-io.minio.GetObjectLockConfigurationArgs-)_ + +Gets object-lock configuration in a bucket. + +__Parameters__ + +| Parameter | Type | Description | +|:----------|:-----------------------------------|:------------| +| ``args`` | _[GetObjectLockConfigurationArgs]_ | Arguments. | + +| Returns | +|:---------------------------------------------------------------| +| _[ObjectLockConfiguration]_ - Default retention configuration. | + +__Example__ +```java +ObjectLockConfiguration config = + minioClient.getObjectLockConfiguration( + GetObjectLockConfigurationArgs.builder().bucket("my-bucketname").build()); +System.out.println("Mode: " + config.mode()); +System.out.println("Duration: " + config.duration().duration() + " " + config.duration().unit()); +``` + + +### listBuckets() +`public List listBuckets()` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#listBuckets--)_ + +Lists bucket information of all buckets. + +| Returns | +|:-----------------------------------------------| +| _List<[Bucket]>_ - List of bucket information. | + +__Example__ +```java +List bucketList = minioClient.listBuckets(); +for (Bucket bucket : bucketList) { + System.out.println(bucket.creationDate() + ", " + bucket.name()); +} +``` + + +### listBuckets(ListBucketsArgs args) +`public List listBuckets(ListBucketsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#listBuckets-io.minio.ListBucketsArgs-)_ + +Lists bucket information of all buckets. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:--------------------|:------------| +| ``args`` | _[ListBucketsArgs]_ | Arguments. | + +| Returns | +|:-----------------------------------------------| +| _List<[Bucket]>_ - List of bucket information. | + +__Example__ +```java +List bucketList = + minioClient.listBuckets(ListBuckets.builder().extraHeaders(headers).build()); +for (Bucket bucket : bucketList) { + System.out.println(bucket.creationDate() + ", " + bucket.name()); +} +``` + + +### listenBucketNotification(ListenBucketNotificationArgs args) +`public CloseableIterator> listenBucketNotification(ListenBucketNotificationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#listenBucketNotification-io.minio.ListenBucketNotificationArgs-)_ + +Listens events of object prefix and suffix of a bucket. The returned closable iterator is lazily evaluated hence its required to iterate to get new records and must be used with try-with-resource to release underneath network resources. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:---------------------------------|:------------| +| ``args`` | _[ListenBucketNotificationArgs]_ | Arguments. | + +| Returns | +|:--------------------------------------------------------------------------------------------------------| +| _[CloseableIterator]<[Result]<[NotificationRecords]>>_ - Lazy closable iterator contains event records. | + +__Example__ +```java +String[] events = {"s3:ObjectCreated:*", "s3:ObjectAccessed:*"}; +try (CloseableIterator> ci = + minioClient.listenBucketNotification( + ListenBucketNotificationArgs.builder() + .bucket("bucketName") + .prefix("") + .suffix("") + .events(events) + .build())) { + while (ci.hasNext()) { + NotificationRecords records = ci.next().get(); + for (Event event : records.events()) { + System.out.println("Event " + event.eventType() + " occurred at " + event.eventTime() + + " for " + event.bucketName() + "/" + event.objectName()); + } + } +} +``` + + +### listObjects(ListObjectsArgs args) +`public Iterable> listObjects(ListObjectsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#listObjects-io.minio.ListObjectsArgs-)_ + +Lists object information of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:-----------------|:--------------------|:--------------------------| +| ``args`` | _[ListObjectsArgs]_ | Arguments to list objects | + +| Returns | +|:--------------------------------------------------------------------------| +| _Iterable<[Result]<[Item]>>_ - Lazy iterator contains object information. | + +__Example__ +```java +// Lists objects information. +Iterable> results = minioClient.listObjects( + ListObjectsArgs.builder().bucket("my-bucketname").build()); + +// Lists objects information recursively. +Iterable> results = minioClient.listObjects( + ListObjectsArgs.builder().bucket("my-bucketname").recursive(true).build()); + +// Lists maximum 100 objects information whose names starts with 'E' and after 'ExampleGuide.pdf'. +Iterable> results = minioClient.listObjects( + ListObjectsArgs.builder() + .bucket("my-bucketname") + .startAfter("ExampleGuide.pdf") + .prefix("E") + .maxKeys(100) + .build()); + +// Lists maximum 100 objects information with version whose names starts with 'E' and after +// 'ExampleGuide.pdf'. +Iterable> results = minioClient.listObjects( + ListObjectsArgs.builder() + .bucket("my-bucketname") + .startAfter("ExampleGuide.pdf") + .prefix("E") + .maxKeys(100) + .includeVersions(true) + .build()); +``` + +### makeBucket(MakeBucketArgs args) +`public void makeBucket(MakeBucketArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#makeBucket-io.minio.MakeBucketArgs-)_ + +Creates a bucket with given region and object lock feature enabled. + +__Parameters__ + +| Parameter | Type | Description | +|:---------------|:-------------------|:---------------------------| +| ``args`` | _[MakeBucketArgs]_ | Arguments to create bucket | + +__Example__ + +```java +// Create bucket with default region. +minioClient.makeBucket( + MakeBucketArgs.builder() + .bucket("my-bucketname") + .build()); + +// Create bucket with specific region. +minioClient.makeBucket( + MakeBucketArgs.builder() + .bucket("my-bucketname") + .region("us-west-1") + .build()); + +// Create object-lock enabled bucket with specific region. +minioClient.makeBucket( + MakeBucketArgs.builder() + .bucket("my-bucketname") + .region("us-west-1") + .objectLock(true) + .build()); +``` + + +### removeBucket(RemoveBucketArgs args) +`public void removeBucket(RemoveBucketArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#removeBucket-io.minio.RemoveBucketArgs-)_ + +Removes an empty bucket. + +__Parameters__ + +| Parameter | Type | Description | +|:-------------|:---------------------|:----------------| +| ``args`` | _[RemoveBucketArgs]_ | Arguments. | + +__Example__ +```java +minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build()); +``` + + +### setBucketEncryption(SetBucketEncryptionArgs args) +`public void setBucketEncryption(SetBucketEncryptionArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setBucketEncryption-io.minio.SetBucketEncryptionArgs-)_ + +Sets encryption configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:----------------------------|:------------| +| ``args`` | _[SetBucketEncryptionArgs]_ | Arguments. | + +__Example__ +```java +minioClient.setBucketEncryption( + SetBucketEncryptionArgs.builder().bucket("my-bucketname").config(config).build()); + ``` + + +### setBucketLifecycle(SetBucketLifecycleArgs args) +`public void setBucketLifecycle(SetBucketLifecycleArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setBucketLifecycle-io.minio.SetBucketLifecycleArgs-)_ + +Sets lifecycle configuration to a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:---------------------------|:------------| +| ``args`` | _[SetBucketLifecycleArgs]_ | Arguments. | + +__Example__ +```java +List rules = new LinkedList<>(); +rules.add( + new LifecycleRule( + Status.ENABLED, + null, + null, + new RuleFilter("documents/"), + "rule1", + null, + null, + new Transition((ZonedDateTime) null, 30, "GLACIER"))); +rules.add( + new LifecycleRule( + Status.ENABLED, + null, + new Expiration((ZonedDateTime) null, 365, null), + new RuleFilter("logs/"), + "rule2", + null, + null, + null)); +LifecycleConfiguration config = new LifecycleConfiguration(rules); +minioClient.setBucketLifecycle( + SetBucketLifecycleArgs.builder().bucket("my-bucketname").config(config).build()); +``` + + +### setBucketNotification(SetBucketNotificationArgs args) +`public void setBucketNotification(SetBucketNotificationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setBucketNotification-io.minio.SetBucketNotificationArgs-)_ + +Sets notification configuration to a bucket. + +__Parameters__ + +| Parameter | Type | Description | +|:----------|:------------------------------|:------------| +| ``args`` | _[SetBucketNotificationArgs]_ | Arguments. | + +__Example__ +```java +List eventList = new LinkedList<>(); +eventList.add(EventType.OBJECT_CREATED_PUT); +eventList.add(EventType.OBJECT_CREATED_COPY); + +QueueConfiguration queueConfiguration = new QueueConfiguration(); +queueConfiguration.setQueue("arn:minio:sqs::1:webhook"); +queueConfiguration.setEvents(eventList); +queueConfiguration.setPrefixRule("images"); +queueConfiguration.setSuffixRule("pg"); + +List queueConfigurationList = new LinkedList<>(); +queueConfigurationList.add(queueConfiguration); + +NotificationConfiguration config = new NotificationConfiguration(); +config.setQueueConfigurationList(queueConfigurationList); + +minioClient.setBucketNotification( + SetBucketNotificationArgs.builder().bucket("my-bucketname").config(config).build()); +``` + + +### setBucketPolicy(SetBucketPolicyArgs args) +`public void setBucketPolicy(SetBucketPolicyArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setBucketPolicy-io.minio.SetBucketPolicyArgs-)_ + +Sets bucket policy configuration to a bucket. + +__Parameters__ + +| Parameter | Type | Description | +|:----------|:------------------------|:------------| +| ``args`` | _[SetBucketPolicyArgs]_ | Arguments. | + +__Example__ +```java +// Assume policyJson contains below JSON string; +// { +// "Statement": [ +// { +// "Action": [ +// "s3:GetBucketLocation", +// "s3:ListBucket" +// ], +// "Effect": "Allow", +// "Principal": "*", +// "Resource": "arn:aws:s3:::my-bucketname" +// }, +// { +// "Action": "s3:GetObject", +// "Effect": "Allow", +// "Principal": "*", +// "Resource": "arn:aws:s3:::my-bucketname/myobject*" +// } +// ], +// "Version": "2012-10-17" +// } +// +minioClient.setBucketPolicy( + SetBucketPolicyArgs.builder().bucket("my-bucketname").config(policyJson).build()); +``` + + +### setBucketReplication(SetBucketReplicationArgs args) +`public void setBucketReplication(SetBucketReplicationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setBucketReplication-io.minio.SetBucketReplicationArgs-)_ + +Sets bucket replication configuration to a bucket. + +__Parameters__ + +| Parameter | Type | Description | +|:----------|:-----------------------------|:------------| +| ``args`` | _[SetBucketReplicationArgs]_ | Arguments. | + +__Example__ +```java +Map tags = new HashMap<>(); +tags.put("key1", "value1"); +tags.put("key2", "value2"); + +ReplicationRule rule = + new ReplicationRule( + new DeleteMarkerReplication(Status.DISABLED), + new ReplicationDestination( + null, null, "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", null, null, null, null), + null, + new RuleFilter(new AndOperator("TaxDocs", tags)), + "rule1", + null, + 1, + null, + Status.ENABLED); + +List rules = new LinkedList<>(); +rules.add(rule); + +ReplicationConfiguration config = + new ReplicationConfiguration("REPLACE-WITH-ACTUAL-ROLE", rules); + +minioClient.setBucketReplication( + SetBucketReplicationArgs.builder().bucket("my-bucketname").config(config).build()); +``` + + +### setBucketTags(SetBucketTagsArgs args) +`public void setBucketTags(SetBucketTagsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setBucketTags-io.minio.SetBucketTagsArgs-)_ + +Sets tags to a bucket. + +__Parameters__ + +| Parameter | Type | Description | +|:----------|:----------------------|:------------| +| ``args`` | _[SetBucketTagsArgs]_ | Arguments. | + +__Example__ +```java +Map map = new HashMap<>(); +map.put("Project", "Project One"); +map.put("User", "jsmith"); +minioClient.setBucketTags(SetBucketTagsArgs.builder().bucket("my-bucketname").tags(map).build()); +``` + + +### setBucketVersioning(SetBucketVersioningArgs args) +`public void setBucketVersioning(SetBucketVersioningArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setBucketVersioning-io.minio.SetBucketVersioningArgs-)_ + +Sets versioning configuration of a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:----------------------------|:------------| +| ``args`` | _[SetBucketVersioningArgs]_ | Arguments. | + +__Example__ +```java +minioClient.setBucketVersioning( + SetBucketVersioningArgs.builder().bucket("my-bucketname").config(config).build()); + ``` + + +### setObjectLockConfiguration(SetObjectLockConfigurationArgs args) +`public void setObjectLockConfiguration(SetObjectLockConfigurationArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setObjectLockConfiguration-io.minio.SetObjectLockConfigurationArgs-)_ + +Sets object-lock configuration in a bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:-----------------------------------|:------------| +| ``args`` | _[SetObjectLockConfigurationArgs]_ | Arguments. | + +__Example__ +```java +ObjectLockConfiguration config = + new ObjectLockConfiguration(RetentionMode.COMPLIANCE, new RetentionDurationDays(100)); +minioClient.setObjectLockConfiguration( + SetObjectLockConfigurationArgs.builder().bucket("my-bucketname").config(config).build()); +``` + +## 3. Object operations + + +### composeObject(ComposeObjectArgs args) +`public ObjectWriteResponse composeObject(ComposeObjectArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#composeObject-io.minio.ComposeObjectArgs--)_ + +Creates an object by combining data from different source objects using server-side copy. + + __Parameters__ +| Param | Type | Description | +|:---------------|:-------------------------|:--------------| +| ``args`` | _[ComposeObjectArgs]_ | Arguments. | + +| Returns | +|:-----------------------------------------------------------------| +| _[ObjectWriteResponse]_ - Contains information of created object.| + +__Example__ + ```java +List sourceObjectList = new ArrayList(); +sourceObjectList.add( + ComposeSource.builder().bucket("my-job-bucket").object("my-objectname-part-one").build()); +sourceObjectList.add( + ComposeSource.builder().bucket("my-job-bucket").object("my-objectname-part-two").build()); +sourceObjectList.add( + ComposeSource.builder().bucket("my-job-bucket").object("my-objectname-part-three").build()); + +// Create my-bucketname/my-objectname by combining source object list. +minioClient.composeObject( + ComposeObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .sources(sourceObjectList) + .build()); + +// Create my-bucketname/my-objectname with user metadata by combining source object +// list. +Map userMetadata = new HashMap<>(); +userMetadata.put("My-Project", "Project One"); +minioClient.composeObject( + ComposeObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .sources(sourceObjectList) + .userMetadata(userMetadata) + .build()); + +// Create my-bucketname/my-objectname with user metadata and server-side encryption +// by combining source object list. +minioClient.composeObject( + ComposeObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .sources(sourceObjectList) + .userMetadata(userMetadata) + .ssec(sse) + .build()); +``` + + +### copyObject(CopyObjectArgs args) +`public ObjectWriteResponse copyObject(CopyObjectArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#copyObject-io.minio.CopyObjectArgs-)_ + +Creates an object by server-side copying data from another object. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:-------------------|:------------| +| ``args`` | _[CopyObjectArgs]_ | Arguments. | + +| Returns | +|:-----------------------------------------------------------------| +| _[ObjectWriteResponse]_ - Contains information of created object.| + +__Example__ + +```java +// Create object "my-objectname" in bucket "my-bucketname" by copying from object +// "my-objectname" in bucket "my-source-bucketname". +minioClient.copyObject( + CopyObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .srcBucket("my-source-bucketname") + .build()); + +// Create object "my-objectname" in bucket "my-bucketname" by copying from object +// "my-source-objectname" in bucket "my-source-bucketname". +minioClient.copyObject( + CopyObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .srcBucket("my-source-bucketname") + .srcObject("my-source-objectname") + .build()); + +// Create object "my-objectname" in bucket "my-bucketname" with server-side encryption by +// copying from object "my-objectname" in bucket "my-source-bucketname". +minioClient.copyObject( + CopyObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .srcBucket("my-source-bucketname") + .sse(sse) + .build()); + +// Create object "my-objectname" in bucket "my-bucketname" by copying from SSE-C encrypted +// object "my-source-objectname" in bucket "my-source-bucketname". +minioClient.copyObject( + CopyObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .srcBucket("my-source-bucketname") + .srcObject("my-source-objectname") + .srcSsec(ssec) + .build()); + +// Create object "my-objectname" in bucket "my-bucketname" with custom headers by copying from +// object "my-objectname" in bucket "my-source-bucketname" using conditions. +minioClient.copyObject( + CopyObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .srcBucket("my-source-bucketname") + .headers(headers) + .srcMatchETag(etag) + .build()); +``` + + +### deleteObjectTags(DeleteObjectTagsArgs args) +`private void deleteObjectTags(DeleteObjectTagsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#deleteObjectTags-io.minio.DeleteObjectTagsArgs-)_ + +Deletes tags of an object. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:-------------------------|:------------| +| ``args`` | _[DeleteObjectTagsArgs]_ | Arguments. | + +__Example__ +```java +minioClient.deleteObjectTags( + DeleteObjectArgs.builder().bucket("my-bucketname").object("my-objectname").build()); +``` + + +### disableObjectLegalHold(DisableObjectLegalHoldArgs args) +`public void disableObjectLegalHold(DisableObjectLegalHoldArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#disableObjectLegalHold-io.minio.DisableObjectLegalHoldArgs-)_ + +Disables legal hold on an object. + + __Parameters__ + +| Parameter | Type | Description | +|:---------------|:-------------------------------|:-------------| +| ``args`` | _[DisableObjectLegalHoldArgs]_ | Arguments. | + + __Example__ + +```java +// Disables legal hold on an object. +minioClient.disableObjectLegalHold( + DisableObjectLegalHoldArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .build()); +``` + + +### enableObjectLegalHold(EnableObjectLegalHoldArgs args) +`public void enableObjectLegalHold(EnableObjectLegalHoldArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#enableObjectLegalHold-io.minio.EnableObjectLegalHoldArgs-)_ + +Enables legal hold on an object. + + __Parameters__ + +| Parameter | Type | Description | +|:---------------|:------------------------------|:-------------| +| ``args`` | _[EnableObjectLegalHoldArgs]_ | Argumments. | + + __Example__ + ```java + + // Disables legal hold on an object. +minioClient.enableObjectLegalHold( + EnableObjectLegalHoldArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .build()); +``` + + +### getObject(GetObjectArgs args) +`public InputStream getObject(GetObjectArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getObject-io.minio.GetObjectArgs-)_ + +Gets data of an object. Returned `InputStream` must be closed after use to release network resources. + +__Parameters__ +| Parameter | Type | Description | +|:---------------|:----------------|:---------------------------| +| ``args`` | _GetObjectArgs_ | Arguments. | + +| Returns | +|:--------------------------------------| +| _InputStream_ - Contains object data. | + +__Example__ +```java +// get object given the bucket and object name +try (InputStream stream = minioClient.getObject( + GetObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .build())) { + // Read data from stream +} + +// get object data from offset +try (InputStream stream = minioClient.getObject( + GetObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .offset(1024L) + .build())) { + // Read data from stream +} + +// get object data from offset to length +try (InputStream stream = minioClient.getObject( + GetObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .offset(1024L) + .length(4096L) + .build())) { + // Read data from stream +} + +// get data of an SSE-C encrypted object +try (InputStream stream = minioClient.getObject( + GetObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .ssec(ssec) + .build())) { + // Read data from stream +} + +// get object data from offset to length of an SSE-C encrypted object +try (InputStream stream = minioClient.getObject( + GetObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .offset(1024L) + .length(4096L) + .ssec(ssec) + .build())) { + // Read data from stream +} +``` + + +### downloadObject(DownloadObjectArgs args) +`public void downloadObject(DownloadObjectArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getObject-io.minio.DownloadObjectArgs-)_ + +Downloads data of an object to file. + +__Parameters__ +| Parameter | Type | Description | +|:-----------------|:---------------------|:-----------------------------| +| ``args`` | _DownloadObjectArgs_ | Arguments. | + +__Example__ +```java +// Download object given the bucket, object name and output file name +minioClient.downloadObject( + DownloadObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .fileName("my-object-file") + .build()); + +// Download server-side encrypted object in bucket to given file name +minioClient.downloadObject( + DownloadObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .ssec(ssec) + .fileName("my-object-file") + .build()); +``` + + +### getObjectRetention(GetObjectRetentionArgs args) +`public Retention getObjectRetention(GetObjectRetentionArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getObjectRetention-io.minio.GetObjectRetentionArgs-)_ + +Gets retention configuration of an object. + + __Parameters__ + +| Parameter | Type | Description | +|:---------------|:---------------------------|:--------------| +| ``args`` | _[GetObjectRetentionArgs]_ | Arguments. | + +| Returns | +|:------------------------------------------------| +| _[Retention]_ - Object retention configuration. | + + __Example__ + ```java +// Object with version id. +Retention retention = + minioClient.getObjectRetention( + GetObjectRetentionArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .versionId("object-version-id") + .build()); +System.out.println("mode: " + retention.mode() + "until: " + retention.retainUntilDate()); +``` + + +### getObjectTags(GetObjectTagsArgs args) +`public Tags getObjectTags(GetObjectTagsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getObjectTags-io.minio.GetObjectTagsArgs-)_ + +Gets tags of an object. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:----------------------|:------------| +| ``args`` | _[GetObjectTagsArgs]_ | Arguments. | + + +| Returns | +|:-----------------| +| _[Tags]_ - tags. | + +__Example__ +```java +Tags tags = minioClient.getObjectTags( + GetObjectTagsArgs.builder().bucket("my-bucketname").object("my-objectname").build()); +``` + + +### getPresignedObjectUrl(GetPresignedObjectUrlArgs args) +`public String getPresignedObjectUrl(GetPresignedObjectUrlArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getPresignedObjectUrl-io.minio.GetPresignedObjectUrlArgs-)_ + +Gets presigned URL of an object for HTTP method, expiry time and custom request parameters. + + __Parameters__ +| Parameter | Type | Description | +|:------------|:-------------------------------|:-------------| +| ``args`` | _[GetPresignedObjectUrlArgs]_ | Arguments. | + +| Returns | +|:-----------------------| +| _String_ - URL string. | + + __Example__ + ```java +// Get presigned URL string to download 'my-objectname' in 'my-bucketname' +// with an expiration of 2 hours. +// +// Additionally also add 'response-content-type' to dynamically set content-type +// for the server response. +Map reqParams = new HashMap(); +reqParams.put("response-content-type", "application/json"); + +String url = + minioClient.getPresignedObjectUrl( + GetPresignedObjectUrlArgs.builder() + .method(Method.GET) + .bucket("my-bucketname") + .object("my-objectname") + .expiry(2, TimeUnit.HOURS) + .extraQueryParams(reqParams) + .build()); +System.out.println(url); + +// Get presigned URL string to upload 'my-objectname' in 'my-bucketname' +// with an expiration of 1 day. +String url = + minioClient.getPresignedObjectUrl( + GetPresignedObjectUrlArgs.builder() + .method(Method.PUT) + .bucket("my-bucketname") + .object("my-objectname") + .expiry(1, TimeUnit.DAYS) + .build()); +System.out.println(url); + +// Get presigned URL string to lookup metadata for 'my-objectname' in 'my-bucketname' +// with an expiration of 2 hours. +// +// Additionally also add 'response-content-type' to dynamically set content-type +// for the server metadata response. +Map reqParams = new HashMap(); +reqParams.put("response-content-type", "application/json"); + +String url = + minioClient.getPresignedObjectUrl( + GetPresignedObjectUrlArgs.builder() + .method(Method.HEAD) + .bucket("my-bucketname") + .object("my-objectname") + .expiry(2, TimeUnit.HOURS) + .extraQueryParams(reqParams) + .build()); +System.out.println(url); +``` + + +### isObjectLegalHoldEnabled(IsObjectLegalHoldEnabledArgs args) +`public boolean isObjectLegalHoldEnabled(IsObjectLegalHoldEnabledArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#isObjectLegalHoldEnabled-io.minio.IsObjectLegalHoldEnabledArgs-)_ + +Returns true if legal hold is enabled on an object. + + __Parameters__ + +| Parameter | Type | Description | +|:----------|:---------------------------------|:-------------| +| ``args`` | _[IsObjectLegalHoldEnabledArgs]_ | Arguments. | + + +| Returns | +|:-------------------------------------------| +| _boolean_ - True if legal hold is enabled. | + + __Example__ + +```java +boolean status = + s3Client.isObjectLegalHoldEnabled( + IsObjectLegalHoldEnabledArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .versionId("object-versionId") + .build()); +if (status) { + System.out.println("Legal hold is on"); +else { + System.out.println("Legal hold is off"); +} +``` + + +### getPresignedPostFormData(PostPolicy policy) +`public Map getPresignedPostFormData(PostPolicy policy)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#getPresignedPostFormData-io.minio.PostPolicy-)_ + +Gets form-data of [PostPolicy] of an object to upload its data using POST method. + +__Parameters__ +| Parameter | Type | Description | +|:-----------|:---------------|:--------------------------| +| ``policy`` | _[PostPolicy]_ | Post policy of an object. | + +| Returns | +|:----------------------------------------------------------------------------------| +| _Map_ - Contains form-data to upload an object using POST method. | + +__Example__ +```java +// Create new post policy for 'my-bucketname' with 7 days expiry from now. +PostPolicy policy = new PostPolicy("my-bucketname", ZonedDateTime.now().plusDays(7)); + +// Add condition that 'key' (object name) equals to 'my-objectname'. +policy.addEqualsCondition("key", "my-objectname"); + +// Add condition that 'Content-Type' starts with 'image/'. +policy.addStartsWithCondition("Content-Type", "image/"); + +// Add condition that 'content-length-range' is between 64kiB to 10MiB. +policy.addContentLengthRangeCondition(64 * 1024, 10 * 1024 * 1024); + +Map formData = minioClient.getPresignedPostFormData(policy); + +// Upload an image using POST object with form-data. +MultipartBody.Builder multipartBuilder = new MultipartBody.Builder(); +multipartBuilder.setType(MultipartBody.FORM); +for (Map.Entry entry : formData.entrySet()) { + multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue()); +} +multipartBuilder.addFormDataPart("key", "my-objectname"); +multipartBuilder.addFormDataPart("Content-Type", "image/png"); + +// "file" must be added at last. +multipartBuilder.addFormDataPart( + "file", "my-objectname", RequestBody.create(new File("Pictures/avatar.png"), null)); + +Request request = + new Request.Builder() + .url("https://play.min.io/my-bucketname") + .post(multipartBuilder.build()) + .build(); +OkHttpClient httpClient = new OkHttpClient().newBuilder().build(); +Response response = httpClient.newCall(request).execute(); +if (response.isSuccessful()) { + System.out.println("Pictures/avatar.png is uploaded successfully using POST object"); +} else { + System.out.println("Failed to upload Pictures/avatar.png"); +} +``` + + +### putObject(PutObjectArgs args) +`public ObjectWriteResponse putObject(PutObjectArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#putObject-io.minio.PutObjectArgs-)_ + +Uploads given stream as object in bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:------------------|:------------| +| ``args`` | _[PutObjectArgs]_ | Arguments. | + +| Returns | +|:-----------------------------------------------------------------| +| _[ObjectWriteResponse]_ - Contains information of created object.| + +__Example__ +```java +// Upload known sized input stream. +minioClient.putObject( + PutObjectArgs.builder().bucket("my-bucketname").object("my-objectname").stream( + inputStream, size, -1) + .contentType("video/mp4") + .build()); + +// Upload unknown sized input stream. +minioClient.putObject( + PutObjectArgs.builder().bucket("my-bucketname").object("my-objectname").stream( + inputStream, -1, 10485760) + .contentType("video/mp4") + .build()); + +// Create object ends with '/' (also called as folder or directory). +minioClient.putObject( + PutObjectArgs.builder().bucket("my-bucketname").object("path/to/").stream( + new ByteArrayInputStream(new byte[] {}), 0, -1) + .build()); + +// Upload input stream with headers and user metadata. +Map headers = new HashMap<>(); +headers.put("X-Amz-Storage-Class", "REDUCED_REDUNDANCY"); +Map userMetadata = new HashMap<>(); +userMetadata.put("My-Project", "Project One"); +minioClient.putObject( + PutObjectArgs.builder().bucket("my-bucketname").object("my-objectname").stream( + inputStream, size, -1) + .headers(headers) + .userMetadata(userMetadata) + .build()); + +// Upload input stream with server-side encryption. +minioClient.putObject( + PutObjectArgs.builder().bucket("my-bucketname").object("my-objectname").stream( + inputStream, size, -1) + .sse(sse) + .build()); +``` + + +### uploadObject(UploadObjectArgs args) +`public void uploadObject(UploadObjectArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#uploadObject-io.minio.UploadObjectArgs-)_ + +Uploads contents from a file as object in bucket. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:---------------------|:------------| +| ``args`` | _[UploadObjectArgs]_ | Arguments. | + +__Example__ +```java +// Upload an JSON file. +minioClient.uploadObject( + UploadObjectArgs.builder() + .bucket("my-bucketname").object("my-objectname").filename("person.json").build()); + +// Upload a video file. +minioClient.uploadObject( + UploadObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .filename("my-video.avi") + .contentType("video/mp4") + .build()); +``` + + +### uploadSnowballObjects(UploadSnowballObjectsArgs args) +`public void uploadSnowballObjects(UploadSnowballObjectsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#uploadSnowballObjects-io.minio.UploadSnowballObjectsArgs-)_ + +Uploads multiple objects in a single put call. It is done by creating intermediate TAR file optionally compressed which is uploaded to S3 service. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:------------------------------|:------------| +| ``args`` | _[UploadSnowballObjectsArgs]_ | Arguments. | + +__Example__ +```java +List objects = new ArrayList(); +objects.add( + new SnowballObject( + "my-object-one", + new ByteArrayInputStream("hello".getBytes(StandardCharsets.UTF_8)), + 5, + null)); +objects.add( + new SnowballObject( + "my-object-two", + new ByteArrayInputStream("java".getBytes(StandardCharsets.UTF_8)), + 4, + null)); +minioClient.uploadSnowballObjects( + UploadSnowballObjectsArgs.builder().bucket("my-bucketname").objects(objects).build()); +``` + + +### removeObject(RemoveObjectArgs args) +`public void removeObject(RemoveObjectArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#removeObject-io.minio.RemoveObjectArgs-)_ + +Removes an object. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:---------------------|:------------| +| ``args`` | _[RemoveObjectArgs]_ | Arguments. | + +__Example__ +```java +// Remove object. +minioClient.removeObject( + RemoveObjectArgs.builder().bucket("my-bucketname").object("my-objectname").build()); + +// Remove versioned object. +minioClient.removeObject( + RemoveObjectArgs.builder() + .bucket("my-bucketname") + .object("my-versioned-objectname") + .versionId("my-versionid") + .build()); + +// Remove versioned object bypassing Governance mode. +minioClient.removeObject( + RemoveObjectArgs.builder() + .bucket("my-bucketname") + .object("my-versioned-objectname") + .versionId("my-versionid") + .bypassRetentionMode(true) + .build()); +``` + + +### removeObjects(RemoveObjectsArgs args) +`public Iterable> removeObjects(RemoveObjectsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#removeObjects-io.minio.RemoveObjectsArgs-)_ + +Removes multiple objects lazily. Its required to iterate the returned Iterable to perform removal. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:----------------------|:------------| +| ``args`` | _[RemoveObjectsArgs]_ | Arguments. | + +| Returns | +|:------------------------------------------------------------------------------------| +| _Iterable<[Result]<[DeleteError]>>_ - Lazy iterator contains object removal status. | + +__Example__ +```java +List objects = new LinkedList<>(); +objects.add(new DeleteObject("my-objectname1")); +objects.add(new DeleteObject("my-objectname2")); +objects.add(new DeleteObject("my-objectname3")); +Iterable> results = + minioClient.removeObjects( + RemoveObjectsArgs.builder().bucket("my-bucketname").objects(objects).build()); +for (Result result : results) { + DeleteError error = result.get(); + System.out.println( + "Error in deleting object " + error.objectName() + "; " + error.message()); +} +``` + + +### selectObjectContent(SelectObjectContentArgs args) +`public SelectResponseStream selectObjectContent(SelectObjectContentArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#selectObjectContent-io.minio.SelectObjectContentArgs-)_ + +Selects content of a object by SQL expression. + +__Parameters__ + +| Parameter | Type | Description | +|:--------------------|:------------------------------------|:--------------------------------------| +| ``args`` | _[SelectObjectContentArgs]_ | Arguments. | + +| Returns | +|:-------------------------------------------------------------------| +| _[SelectResponseStream]_ - Contains filtered records and progress. | + +__Example__ +```java +String sqlExpression = "select * from S3Object"; +InputSerialization is = new InputSerialization(null, false, null, null, FileHeaderInfo.USE, null, null, null); +OutputSerialization os = new OutputSerialization(null, null, null, QuoteFields.ASNEEDED, null); +SelectResponseStream stream = + minioClient.selectObjectContent( + SelectObjectContentArgs.builder() + .bucket("my-bucketname") + .object("my-objectName") + .sqlExpression(sqlExpression) + .inputSerialization(is) + .outputSerialization(os) + .requestProgress(true) + .build()); + +byte[] buf = new byte[512]; +int bytesRead = stream.read(buf, 0, buf.length); +System.out.println(new String(buf, 0, bytesRead, StandardCharsets.UTF_8)); + +Stats stats = stream.stats(); +System.out.println("bytes scanned: " + stats.bytesScanned()); +System.out.println("bytes processed: " + stats.bytesProcessed()); +System.out.println("bytes returned: " + stats.bytesReturned()); + +stream.close(); +``` + + +### setObjectRetention(SetObjectRetentionArgs args) +`public void setObjectLockRetention(SetObjectRetentionArgs)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setObjectRetention-io.minio.SetObjectRetentionArgs-)_ + +Sets retention configuration to an object. + + __Parameters__ + +| Parameter | Type | Description | +|:-----------------|:---------------------------|:-------------| +| ``args`` | _[SetObjectRetentionArgs]_ | Arguments. | + + __Example__ +```java +Retention retention = new Retention(RetentionMode.COMPLIANCE, ZonedDateTime.now().plusYears(1)); +minioClient.setObjectRetention( + SetObjectRetentionArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .config(retention) + .bypassGovernanceMode(true) + .build()); +``` + + +### setObjectTags(SetObjectTagsArgs args) +`public void setObjectTags(SetObjectTagsArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#setObjectTags-io.minio.SetObjectTagsArgs-)_ + +Sets tags to an object. + +__Parameters__ + +| Parameter | Type | Description | +|:----------|:----------------------|:------------| +| ``args`` | _[SetObjectTagsArgs]_ | Arguments. | + +__Example__ +```java +Map map = new HashMap<>(); +map.put("Project", "Project One"); +map.put("User", "jsmith"); +minioClient.setObjectTags( + SetObjectTagsArgs.builder().bucket("my-bucketname").object("my-objectname").tags(map).build()); +``` + + +### statObject(StatObjectArgs args) +`public ObjectStat statObject(StatObjectArgs args)` _[[Javadoc]](http://minio.github.io/minio-java/io/minio/MinioClient.html#statObject-io.minio.StatObjectArgs-)_ + +Gets object information and metadata of an object. + +__Parameters__ +| Parameter | Type | Description | +|:----------|:-------------------|:------------| +| ``args`` | _[StatObjectArgs]_ | Arguments. | + +| Returns | +|:------------------------------------------------------------| +| _[ObjectStat]_ - Populated object information and metadata. | + +__Example__ +```java +// Get information of an object. +ObjectStat objectStat = + minioClient.statObject( + StatObjectArgs.builder().bucket("my-bucketname").object("my-objectname").build()); + +// Get information of SSE-C encrypted object. +ObjectStat objectStat = + minioClient.statObject( + StatObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .ssec(ssec) + .build()); + +// Get information of a versioned object. +ObjectStat objectStat = + minioClient.statObject( + StatObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .versionId("version-id") + .build()); + +// Get information of a SSE-C encrypted versioned object. +ObjectStat objectStat = + minioClient.statObject( + StatObjectArgs.builder() + .bucket("my-bucketname") + .object("my-objectname") + .versionId("version-id") + .ssec(ssec) + .build()); +``` + +## 5. Explore Further +- [Build your own Photo API Service - Full Application Example ](https://github.com/minio/minio-java-rest-example) +- [Complete JavaDoc](http://minio.github.io/minio-java/) + +[constructor-1]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.lang.String- +[constructor-2]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.net.URL- +[constructor-3]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-okhttp3.HttpUrl- +[constructor-4]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.lang.String-java.lang.String-java.lang.String- +[constructor-5]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.lang.String-int-java.lang.String-java.lang.String- +[constructor-6]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.lang.String-java.lang.String-java.lang.String-boolean- +[constructor-7]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.lang.String-int-java.lang.String-java.lang.String-java.lang.String-boolean- +[constructor-8]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-okhttp3.HttpUrl-java.lang.String-java.lang.String- +[constructor-9]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.net.URL-java.lang.String-java.lang.String- +[constructor-10]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.lang.String-java.lang.String-java.lang.String-java.lang.String- +[constructor-11]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.lang.String-int-java.lang.String-java.lang.String-java.lang.String-boolean- +[constructor-12]: http://minio.github.io/minio-java/io/minio/MinioClient.html#MinioClient-java.lang.String-java.lang.Integer-java.lang.String-java.lang.String-java.lang.String-java.lang.Boolean-okhttp3.OkHttpClient- +[NotificationConfiguration]: http://minio.github.io/minio-java/io/minio/messages/NotificationConfiguration.html +[ObjectLockConfiguration]: http://minio.github.io/minio-java/io/minio/messages/ObjectLockConfiguration.html +[Bucket]: http://minio.github.io/minio-java/io/minio/messages/Bucket.html +[CloseableIterator]: http://minio.github.io/minio-java/io/minio/CloseableIterator.html +[Result]: http://minio.github.io/minio-java/io/minio/Result.html +[NotificationRecords]: http://minio.github.io/minio-java/io/minio/messages/NotificationRecords.html +[Upload]: http://minio.github.io/minio-java/io/minio/messages/Upload.html +[Item]: http://minio.github.io/minio-java/io/minio/messages/Item.html +[ComposeSource]: http://minio.github.io/minio-java/io/minio/ComposeSource.html +[ServerSideEncryption]: http://minio.github.io/minio-java/io/minio/ServerSideEncryption.html +[ServerSideEncryptionCustomerKey]: http://minio.github.io/minio-java/io/minio/ServerSideEncryptionCustomerKey.html +[CopyConditions]: http://minio.github.io/minio-java/io/minio/CopyConditions.html +[PostPolicy]: http://minio.github.io/minio-java/io/minio/PostPolicy.html +[PutObjectOptions]: http://minio.github.io/minio-java/io/minio/PutObjectOptions.html +[InputSerialization]: http://minio.github.io/minio-java/io/minio/messages/InputSerialization.html +[OutputSerialization]: http://minio.github.io/minio-java/io/minio/messages/OutputSerialization.html +[Retention]: http://minio.github.io/minio-java/io/minio/messages/Retention.html +[ObjectStat]: http://minio.github.io/minio-java/io/minio/ObjectStat.html +[DeleteError]: http://minio.github.io/minio-java/io/minio/messages/DeleteError.html +[SelectResponseStream]: http://minio.github.io/minio-java/io/minio/SelectResponseStream.html +[MakeBucketArgs]: http://minio.github.io/minio-java/io/minio/MakeBucketArgs.html +[ListObjectsArgs]: http://minio.github.io/minio-java/io/minio/ListObjectsArgs.html +[RemoveBucketArgs]: http://minio.github.io/minio-java/io/minio/RemoveBucketArgs.html +[SetObjectRetentionArgs]: http://minio.github.io/minio-java/io/minio/SetObjectRetentionArgs.html +[GetObjectRetentionArgs]: http://minio.github.io/minio-java/io/minio/GetObjectRetentionArgs.html +[Method]: http://minio.github.io/minio-java/io/minio/http/Method.html +[StatObjectArgs]: http://minio.github.io/minio-java/io/minio/StatObjectArgs.html +[RemoveObjectArgs]: http://minio.github.io/minio-java/io/minio/RemoveObjectArgs.html +[SseConfiguration]: http://minio.github.io/minio-java/io/minio/messages/SseConfiguration.html +[DeleteBucketEncryptionArgs]: http://minio.github.io/minio-java/io/minio/DeleteBucketEncryptionArgs.html +[GetBucketEncryptionArgs]: http://minio.github.io/minio-java/io/minio/GetBucketEncryptionArgs.html +[SetBucketEncryptionArgs]: http://minio.github.io/minio-java/io/minio/SetBucketEncryptionArgs.html +[Tags]: http://minio.github.io/minio-java/io/minio/messages/Tags.html +[DeleteBucketTagsArgs]: http://minio.github.io/minio-java/io/minio/DeleteBucketTagsArgs.html +[GetBucketTagsArgs]: http://minio.github.io/minio-java/io/minio/GetBucketTagsArgs.html +[SetBucketTagsArgs]: http://minio.github.io/minio-java/io/minio/SetBucketTagsArgs.html +[DeleteObjectTagsArgs]: http://minio.github.io/minio-java/io/minio/DeleteObjectTagsArgs.html +[GetObjectTagsArgs]: http://minio.github.io/minio-java/io/minio/GetObjectTagsArgs.html +[SetObjectTagsArgs]: http://minio.github.io/minio-java/io/minio/SetObjectTagsArgs.html +[LifecycleConfiguration]: http://minio.github.io/minio-java/io/minio/messages/LifecycleConfiguration.html +[DeleteBucketLifecycleArgs]: http://minio.github.io/minio-java/io/minio/DeleteBucketLifecycleArgs.html +[GetBucketLifecycleArgs]: http://minio.github.io/minio-java/io/minio/GetBucketLifecycleArgs.html +[SetBucketLifecycleArgs]: http://minio.github.io/minio-java/io/minio/SetBucketLifecycleArgs.html +[GetBucketPolicyArgs]: http://minio.github.io/minio-java/io/minio/GetBucketPolicyArgs.html +[SetBucketPolicyArgs]: http://minio.github.io/minio-java/io/minio/SetBucketPolicyArgs.html +[DeleteBucketPolicyArgs]: http://minio.github.io/minio-java/io/minio/DeleteBucketPolicyArgs.html +[GetObjectArgs]: http://minio.github.io/minio-java/io/minio/GetObjectArgs.html +[DownloadObjectArgs]: http://minio.github.io/minio-java/io/minio/DownloadObjectArgs.html +[BucketExistsArgs]: http://minio.github.io/minio-java/io/minio/BucketExistsArgs.html +[EnableObjectLegalHoldArgs]: http://minio.github.io/minio-java/io/minio/EnableObjectLegalHoldArgs.html +[DisableObjectLegalHoldArgs]: http://minio.github.io/minio-java/io/minio/DisableObjectLegalHoldArgs.html +[IsObjectLegalHoldEnabledArgs]: http://minio.github.io/minio-java/io/minio/IsObjectLegalHoldEnabledArgs.html +[DeleteBucketNotificationArgs]: http://minio.github.io/minio-java/io/minio/DeleteBucketNotificationArgs.html +[GetBucketNotificationArgs]: http://minio.github.io/minio-java/io/minio/GetBucketNotificationArgs.html +[SetBucketNotificationArgs]: http://minio.github.io/minio-java/io/minio/SetBucketNotificationArgs.html +[ListenBucketNotificationArgs]: http://minio.github.io/minio-java/io/minio/ListenBucketNotificationArgs.html +[SelectObjectContentArgs]: http://minio.github.io/minio-java/io/minio/SelectObjectContentArgs.html +[GetObjectLockConfigurationArgs]: http://minio.github.io/minio-java/io/minio/GetObjectLockConfigurationArgs.html +[SetObjectLockConfigurationArgs]: http://minio.github.io/minio-java/io/minio/SetObjectLockConfigurationArgs.html +[DeleteObjectLockConfigurationArgs]: http://minio.github.io/minio-java/io/minio/DeleteObjectLockConfigurationArgs.html +[GetPresignedObjectUrlArgs]: http://minio.github.io/minio-java/io/minio/GetPresignedObjectUrlArgs.html +[RemoveObjectsArgs]: http://minio.github.io/minio-java/io/minio/RemoveObjectsArgs.html +[CopyObjectArgs]: http://minio.github.io/minio-java/io/minio/CopyObjectArgs.html +[PutObjectArgs]: http://minio.github.io/minio-java/io/minio/PutObjectArgs.html +[UploadObjectArgs]: http://minio.github.io/minio-java/io/minio/UploadObjectArgs.html +[UploadSnowballObjectsArgs]: http://minio.github.io/minio-java/io/minio/UploadSnowballObjectsArgs.html +[ComposeObjectArgs]: http://minio.github.io/minio-java/io/minio/ComposeObjectArgs.html +[ObjectWriteResponse]: http://minio.github.io/minio-java/io/minio/ObjectWriteResponse.html +[ListBucketsArgs]: http://minio.github.io/minio-java/io/minio/ListBucketsArgs.html +[DeleteBucketReplicationArgs]: http://minio.github.io/minio-java/io/minio/DeleteBucketReplicationArgs.html +[GetBucketReplicationArgs]: http://minio.github.io/minio-java/io/minio/GetBucketReplicationArgs.html +[SetBucketReplicationArgs]: http://minio.github.io/minio-java/io/minio/SetBucketReplicationArgs.html +[ReplicationConfiguration]: http://minio.github.io/minio-java/io/minio/messages/ReplicationConfiguration.html +[VersioningConfiguration]: http://minio.github.io/minio-java/io/minio/messages/VersioningConfiguration.html +[GetBucketVersioningArgs]: http://minio.github.io/minio-java/io/minio/GetBucketVersioningArgs.html +[SetBucketVersioningArgs]: http://minio.github.io/minio-java/io/minio/SetBucketVersioningArgs.html diff --git a/source/sdk/java/minio-java.rst b/source/sdk/java/minio-java.rst new file mode 100644 index 00000000..3dfe9557 --- /dev/null +++ b/source/sdk/java/minio-java.rst @@ -0,0 +1,10 @@ +.. _minio-java: + +.. default-domain:: minio + +.. contents:: Table of Contents + :local: + :depth: 2 + +.. include:: /sdk/java/API.md + :parser: myst_parser.sphinx_ diff --git a/source/sdk/minio-drivers.rst b/source/sdk/minio-drivers.rst new file mode 100644 index 00000000..1e35c7c4 --- /dev/null +++ b/source/sdk/minio-drivers.rst @@ -0,0 +1,47 @@ +.. _minio-drivers: + +=============================== +Software Development Kits (SDK) +=============================== + +.. default-domain:: minio + +.. contents:: Table of Contents + :local: + :depth: 2 + +MinIO publishes the following Software Development Kits (SDK): + +.. list-table:: + :header-rows: 1 + :widths: 30 30 40 + :width: 100% + + * - Language + - Reference + - Download + + * - Java (``minio-java``) + - :doc:`MinIO Java SDK Reference ` + - ToDo + + * - Python (``minio-py``) + - :doc:`MinIO Python SDK Reference ` + - ToDo + + * - Go (``minio-go``) + - :doc:`MinIO Go SDK Reference ` + - ToDo + + * - .NET (``minio-dotnet``) + - :doc:`MinIO .NET SDK Reference ` + - ToDo + +.. toctree:: + :titlesonly: + :hidden: + + Java SDK + Python SDK + Go SDK + .NET SDK \ No newline at end of file diff --git a/source/sdk/python/API.md b/source/sdk/python/API.md new file mode 100644 index 00000000..c0ffe0a3 --- /dev/null +++ b/source/sdk/python/API.md @@ -0,0 +1,1853 @@ +# Python Client API Reference [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) + +## 1. Constructor + +### Minio(endpoint, access_key=None, secret_key=None, session_token=None, secure=True, region=None, http_client=None, credentials=None) +Initializes a new client object. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:----------------------------------|:---------------------------------------------------------------------------------| +| `endpoint` | _str_ | Hostname of a S3 service. | +| `access_key` | _str_ | (Optional) Access key (aka user ID) of your account in S3 service. | +| `secret_key` | _str_ | (Optional) Secret Key (aka password) of your account in S3 service. | +| `session_token` | _str_ | (Optional) Session token of your account in S3 service. | +| `secure` | _bool_ | (Optional) Flag to indicate to use secure (TLS) connection to S3 service or not. | +| `region` | _str_ | (Optional) Region name of buckets in S3 service. | +| `http_client` | _urllib3.poolmanager.PoolManager_ | (Optional) Customized HTTP client. | +| `credentials` | _minio.credentials.Provider_ | (Optional) Credentials provider of your account in S3 service. | + + +**NOTE on concurrent usage:** `Minio` object is thread safe when using the Python `threading` library. Specifically, it is **NOT** safe to share it between multiple processes, for example when using `multiprocessing.Pool`. The solution is simply to create a new `Minio` object in each process, and not share it between processes. + +__Example__ + +```py +from minio import Minio + +# Create client with anonymous access. +client = Minio("play.min.io") + +# Create client with access and secret key. +client = Minio("s3.amazonaws.com", "ACCESS-KEY", "SECRET-KEY") + +# Create client with access key and secret key with specific region. +client = Minio( + "play.minio.io:9000", + access_key="Q3AM3UQ867SPQQA43P2F", + secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", + region="my-region", +) + +# Create client with custom HTTP client using proxy server. +import urllib3 +client = Minio( + "SERVER:PORT", + access_key="ACCESS_KEY", + secret_key="SECRET_KEY", + secure=True, + http_client=urllib3.ProxyManager( + "https://PROXYSERVER:PROXYPORT/", + timeout=urllib3.Timeout.DEFAULT_TIMEOUT, + cert_reqs="CERT_REQUIRED", + retries=urllib3.Retry( + total=5, + backoff_factor=0.2, + status_forcelist=[500, 502, 503, 504], + ), + ), +) +``` + +| Bucket operations | Object operations | +|:------------------------------------------------------------|:----------------------------------------------------------------| +| [`make_bucket`](#make_bucket) | [`get_object`](#get_object) | +| [`list_buckets`](#list_buckets) | [`put_object`](#put_object) | +| [`bucket_exists`](#bucket_exists) | [`copy_object`](#copy_object) | +| [`remove_bucket`](#remove_bucket) | [`compose_object`](#compose_object) | +| [`list_objects`](#list_objects) | [`stat_object`](#stat_object) | +| [`get_bucket_versioning`](#get_bucket_versioning) | [`remove_object`](#remove_object) | +| [`set_bucket_versioning`](#set_bucket_versioning) | [`remove_objects`](#remove_objects) | +| [`delete_bucket_replication`](#delete_bucket_replication) | [`fput_object`](#fput_object) | +| [`get_bucket_replication`](#get_bucket_replication) | [`fget_object`](#fget_object) | +| [`set_bucket_replication`](#set_bucket_replication) | [`select_object_content`](#select_object_content) | +| [`delete_bucket_lifecycle`](#delete_bucket_lifecycle) | [`delete_object_tags`](#delete_object_tags) | +| [`get_bucket_lifecycle`](#get_bucket_lifecycle) | [`get_object_tags`](#get_object_tags) | +| [`set_bucket_lifecycle`](#set_bucket_lifecycle) | [`set_object_tags`](#set_object_tags) | +| [`delete_bucket_tags`](#delete_bucket_tags) | [`enable_object_legal_hold`](#enable_object_legal_hold) | +| [`get_bucket_tags`](#get_bucket_tags) | [`disable_object_legal_hold`](#disable_object_legal_hold) | +| [`set_bucket_tags`](#set_bucket_tags) | [`is_object_legal_hold_enabled`](#is_object_legal_hold_enabled) | +| [`delete_bucket_policy`](#delete_bucket_policy) | [`get_object_retention`](#get_object_retention) | +| [`get_bucket_policy`](#get_bucket_policy) | [`set_object_retention`](#set_object_retention) | +| [`set_bucket_policy`](#set_bucket_policy) | [`presigned_get_object`](#presigned_get_object) | +| [`delete_bucket_notification`](#delete_bucket_notification) | [`presigned_put_object`](#presigned_put_object) | +| [`get_bucket_notification`](#get_bucket_notification) | [`presigned_post_policy`](#presigned_post_policy) | +| [`set_bucket_notification`](#set_bucket_notification) | [`get_presigned_url`](#get_presigned_url) | +| [`listen_bucket_notification`](#listen_bucket_notification) | | +| [`delete_bucket_encryption`](#delete_bucket_encryption) | | +| [`get_bucket_encryption`](#get_bucket_encryption) | | +| [`set_bucket_encryption`](#set_bucket_encryption) | | +| [`delete_object_lock_config`](#delete_object_lock_config) | | +| [`get_object_lock_config`](#get_object_lock_config) | | +| [`set_object_lock_config`](#set_object_lock_config) | | + +## 2. Bucket operations + + + +### make_bucket(bucket_name, location='us-east-1', object_lock=False) + +Create a bucket with region and object lock. + +__Parameters__ + +| Param | Type | Description | +|---------------|--------|---------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `location` | _str_ | Region in which the bucket will be created. | +| `object_lock` | _bool_ | Flag to set object-lock feature. | + +__Example__ + +```py +# Create bucket. +client.make_bucket("my-bucket") + +# Create bucket on specific region. +client.make_bucket("my-bucket", "us-west-1") + +# Create bucket with object-lock feature on specific region. +client.make_bucket("my-bucket", "eu-west-2", object_lock=True) +``` + + + +### list_buckets() + +List information of all accessible buckets. + +__Parameters__ + +| Return | +|:-----------------| +| List of _Bucket_ | + +__Example__ + +```py +buckets = client.list_buckets() +for bucket in buckets: + print(bucket.name, bucket.creation_date) +``` + + + +### bucket_exists(bucket_name) + +Check if a bucket exists. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:--------------------| +| `bucket_name` | _str_ | Name of the bucket. | + +__Example__ + +```py +if client.bucket_exists("my-bucket"): + print("my-bucket exists") +else: + print("my-bucket does not exist") +``` + + + +### remove_bucket(bucket_name) + +Remove an empty bucket. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:--------------------| +| `bucket_name` | _str_ | Name of the bucket. | + +__Example__ + +```py +client.remove_bucket("my-bucket") +``` + + + +### list_objects(bucket_name, prefix=None, recursive=False, start_after=None, include_user_meta=False, include_version=False, use_api_v1=False, use_url_encoding_type=True) + +Lists object information of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:------------------------|:-------|:-------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `prefix` | _str_ | Object name starts with prefix. | +| `recursive` | _bool_ | List recursively than directory structure emulation. | +| `start_after` | _str_ | List objects after this key name. | +| `include_user_meta` | _bool_ | MinIO specific flag to control to include user metadata. | +| `include_version` | _bool_ | Flag to control whether include object versions. | +| `use_api_v1` | _bool_ | Flag to control to use ListObjectV1 S3 API or not. | +| `use_url_encoding_type` | _bool_ | Flag to control whether URL encoding type to be used or not. | + +__Return Value__ + +| Return | +|:------------------------| +| An iterator of _Object_ | + +__Example__ + +```py +# List objects information. +objects = client.list_objects("my-bucket") +for obj in objects: + print(obj) + +# List objects information whose names starts with "my/prefix/". +objects = client.list_objects("my-bucket", prefix="my/prefix/") +for obj in objects: + print(obj) + +# List objects information recursively. +objects = client.list_objects("my-bucket", recursive=True) +for obj in objects: + print(obj) + +# List objects information recursively whose names starts with +# "my/prefix/". +objects = client.list_objects( + "my-bucket", prefix="my/prefix/", recursive=True, +) +for obj in objects: + print(obj) + +# List objects information recursively after object name +# "my/prefix/world/1". +objects = client.list_objects( + "my-bucket", recursive=True, start_after="my/prefix/world/1", +) +for obj in objects: + print(obj) +``` + + + +### get_bucket_policy(bucket_name) + +Get bucket policy configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Return Value__ + +| Param | +|:--------------------------------------------| +| Bucket policy configuration as JSON string. | + +__Example__ + +```py +policy = client.get_bucket_policy("my-bucket") +``` + + + +### set_bucket_policy(bucket_name, policy) + +Set bucket policy configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``Policy`` | _str_ | Bucket policy configuration as JSON string. | + +__Example__ + +```py +# Example anonymous read-only bucket policy. +policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": ["s3:GetBucketLocation", "s3:ListBucket"], + "Resource": "arn:aws:s3:::my-bucket", + }, + { + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": "s3:GetObject", + "Resource": "arn:aws:s3:::my-bucket/*", + }, + ], +} +client.set_bucket_policy("my-bucket", json.dumps(policy)) + +# Example anonymous read-write bucket policy. +policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": [ + "s3:GetBucketLocation", + "s3:ListBucket", + "s3:ListBucketMultipartUploads", + ], + "Resource": "arn:aws:s3:::my-bucket", + }, + { + "Effect": "Allow", + "Principal": {"AWS": "*"}, + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + "s3:ListMultipartUploadParts", + "s3:AbortMultipartUpload", + ], + "Resource": "arn:aws:s3:::my-bucket/images/*", + }, + ], +} +client.set_bucket_policy("my-bucket", json.dumps(policy)) +``` + + + +### delete_bucket_policy(bucket_name) + +Delete bucket policy configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +client.delete_bucket_policy("my-bucket") +``` + + + +### get_bucket_notification(bucket_name) + +Get notification configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Return Value__ + +| Param | +|:-----------------------------| +| _NotificationConfig_ object. | + +__Example__ + +```py +config = client.get_bucket_notification("my-bucket") +``` + + + +### set_bucket_notification(bucket_name, config) + +Set notification configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:---------------------|:----------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _NotificationConfig_ | Notification configuration. | + +__Example__ + +```py +config = NotificationConfig( + queue_config_list=[ + QueueConfig( + "QUEUE-ARN-OF-THIS-BUCKET", + ["s3:ObjectCreated:*"], + config_id="1", + prefix_filter_rule=PrefixFilterRule("abc"), + ), + ], +) +client.set_bucket_notification("my-bucket", config) +``` + + + +### delete_bucket_notification(bucket_name) + +Delete notification configuration of a bucket. On success, S3 service stops notification of events previously set of the bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +client.delete_bucket_notification("my-bucket") +``` + + + +### listen_bucket_notification(bucket_name, prefix='', suffix='', events=('s3:ObjectCreated:\*', 's3:ObjectRemoved:\*', 's3:ObjectAccessed:\*')) + +Listen events of object prefix and suffix of a bucket. Caller should iterate returned iterator to read new events. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:-------|:--------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `prefix` | _str_ | Listen events of object starts with prefix. | +| `suffix` | _str_ | Listen events of object ends with suffix. | +| `events` | _list_ | Events to listen. | + +__Return Value__ + +| Param | +|:------------------------------------| +| Iterator of event records as _dict_ | + +```py +with client.listen_bucket_notification( + "my-bucket", + prefix="my-prefix/", + events=["s3:ObjectCreated:*", "s3:ObjectRemoved:*"], +) as events: + for event in events: + print(event) +``` + + + +### get_bucket_encryption(bucket_name) + +Get encryption configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Return Value__ + +| Param | +|:--------------------| +| _SSEConfig_ object. | + +__Example__ + +```py +config = client.get_bucket_encryption("my-bucket") +``` + + + +### set_bucket_encryption(bucket_name, config) + +Set encryption configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------------|:--------------------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _SSEConfig_ | Server-side encryption configuration. | + +__Example__ + +```py +client.set_bucket_encryption( + "my-bucket", SSEConfig(Rule.new_sse_s3_rule()), +) +``` + + + +### delete_bucket_encryption(bucket_name) + +Delete encryption configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +client.delete_bucket_encryption("my-bucket") +``` + + + +### get_bucket_versioning(bucket_name) + +Get versioning configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +config = client.get_bucket_versioning("my-bucket") +print(config.status) +``` + + + +### set_bucket_versioning(bucket_name, config) + +Set versioning configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:-------------------|:--------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _VersioningConfig_ | Versioning configuration. | + +__Example__ + +```py +client.set_bucket_versioning("my-bucket", VersioningConfig(ENABLED)) +``` + + + +### delete_bucket_replication(bucket_name) + +Delete replication configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +client.delete_bucket_replication("my-bucket") +``` + + + +### get_bucket_replication(bucket_name) + +Get replication configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +| Return | +|:----------------------------------------| +| _ReplicationConfig_ object. | + +__Example__ + +```py +config = client.get_bucket_replication("my-bucket") +``` + + + +### set_bucket_replication(bucket_name, config) + +Set replication configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:--------------------|:---------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _ReplicationConfig_ | Replication configuration. | + +__Example__ + +```py +config = ReplicationConfig( + "REPLACE-WITH-ACTUAL-ROLE", + [ + Rule( + Destination( + "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", + ), + ENABLED, + delete_marker_replication=DeleteMarkerReplication( + DISABLED, + ), + rule_filter=Filter( + AndOperator( + "TaxDocs", + {"key1": "value1", "key2": "value2"}, + ), + ), + rule_id="rule1", + priority=1, + ), + ], +) +client.set_bucket_replication("my-bucket", config) +``` + + + +### delete_bucket_lifecycle(bucket_name) + +Delete lifecycle configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +client.delete_bucket_lifecycle("my-bucket") +``` + + + +### get_bucket_lifecycle(bucket_name) + +Get lifecycle configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +| Return | +|:--------------------------| +| _LifecycleConfig_ object. | + + +__Example__ + +```py +config = client.get_bucket_lifecycle("my-bucket") +``` + + + +### set_bucket_lifecycle(bucket_name, config) + +Set lifecycle configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------------------|:-------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _LifecycleConfig_ | Lifecycle configuration. | + +__Example__ + +```py +config = LifecycleConfig( + [ + Rule( + ENABLED, + rule_filter=Filter(prefix="documents/"), + rule_id="rule1", + transition=Transition(days=30, storage_class="GLACIER"), + ), + Rule( + ENABLED, + rule_filter=Filter(prefix="logs/"), + rule_id="rule2", + expiration=Expiration(days=365), + ), + ], +) +client.set_bucket_lifecycle("my-bucket", config) +``` + + + +### delete_bucket_tags(bucket_name) + +Delete tags configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +client.delete_bucket_tags("my-bucket") +``` + + + +### get_bucket_tags(bucket_name) + +Get tags configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +| Return | +|:---------------| +| _Tags_ object. | + +__Example__ + +```py +tags = client.get_bucket_tags("my-bucket") +``` + + + +### set_bucket_tags(bucket_name, tags) + +Set tags configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:-------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``tags`` | _Tags_ | Tags configuration. | + +__Example__ + +```py +tags = Tags.new_bucket_tags() +tags["Project"] = "Project One" +tags["User"] = "jsmith" +client.set_bucket_tags("my-bucket", tags) +``` + + + +### delete_object_lock_config(bucket_name) + +Delete object-lock configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +__Example__ + +```py +client.delete_object_lock_config("my-bucket") +``` + + + +### get_object_lock_config(bucket_name) + +Get object-lock configuration of a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:--------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | + +| Return | +|:---------------------------| +| _ObjectLockConfig_ object. | + +__Example__ + +```py +config = client.get_object_lock_config("my-bucket") +``` + + + +### set_object_lock_config(bucket_name, config) + +Set object-lock configuration to a bucket. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:-------------------|:---------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``config`` | _ObjectLockConfig_ | Object-Lock configuration. | + +__Example__ + +```py +config = ObjectLockConfig(GOVERNANCE, 15, DAYS) +client.set_object_lock_condig("my-bucket", config) +``` + +## 3. Object operations + + + +### get_object(bucket_name, object_name, offset=0, length=0, request_headers=None, ssec=None, version_id=None, extra_query_params=None) + +Gets data from offset to length of an object. Returned response should be closed after use to release network resources. To reuse the connection, it's required to call `response.release_conn()` explicitly. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:-----------------|:-----------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `offset` | _int_ | Start byte position of object data. | +| `length` | _int_ | Number of bytes of object data from offset. | +| `request_headers` | _dict_ | Any additional headers to be added with GET request. | +| `ssec` | _SseCustomerKey_ | Server-side encryption customer key. | +| `version_id` | _str_ | Version-ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | + +__Return Value__ + +| Return | +|:----------------------------------------| +| _urllib3.response.HTTPResponse_ object. | + +__Example__ + +```py +# Get data of an object. +try: + response = client.get_object("my-bucket", "my-object") + # Read data from response. +finally: + response.close() + response.release_conn() + +# Get data of an object of version-ID. +try: + response = client.get_object( + "my-bucket", "my-object", + version_id="dfbd25b3-abec-4184-a4e8-5a35a5c1174d", + ) + # Read data from response. +finally: + response.close() + response.release_conn() + +# Get data of an object from offset and length. +try: + response = client.get_object( + "my-bucket", "my-object", offset=512, length=1024, + ) + # Read data from response. +finally: + response.close() + response.release_conn() + +# Get data of an SSE-C encrypted object. +try: + response = client.get_object( + "my-bucket", "my-object", + ssec=SseCustomerKey(b"32byteslongsecretkeymustprovided"), + ) + # Read data from response. +finally: + response.close() + response.release_conn() +``` + + + +### select_object_content(bucket_name, object_name, request) + +Select content of an object by SQL expression. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:----------------|:---------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `request` | _SelectRequest_ | Select request. | + +__Return Value__ + +| Return | +|:-------------------------------------------------------------------------------------| +| A reader contains requested records and progress information as _SelectObjectReader_ | + +__Example__ + +```py +with client.select_object_content( + "my-bucket", + "my-object.csv", + SelectRequest( + "select * from S3Object", + CSVInputSerialization(), + CSVOutputSerialization(), + request_progress=True, + ), +) as result: + for data in result.stream(): + print(data.decode()) + print(result.stats()) +``` + + + +### fget_object(bucket_name, object_name, file_path, request_headers=None, ssec=None, version_id=None, extra_query_params=None, tmp_file_path=None) +Downloads data of an object to file. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:-----------------|:-----------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `file_path` | _str_ | Name of file to download. | +| `request_headers` | _dict_ | Any additional headers to be added with GET request. | +| `ssec` | _SseCustomerKey_ | Server-side encryption customer key. | +| `version_id` | _str_ | Version-ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | +| `tmp_file_path` | _str_ | Path to a temporary file. | + +__Return Value__ + +| Return | +|:-------------------------------| +| Object information as _Object_ | + +__Example__ + +```py +# Download data of an object. +client.fget_object("my-bucket", "my-object", "my-filename") + +# Download data of an object of version-ID. +client.fget_object( + "my-bucket", "my-object", "my-filename", + version_id="dfbd25b3-abec-4184-a4e8-5a35a5c1174d", +) + +# Download data of an SSE-C encrypted object. +client.fget_object( + "my-bucket", "my-object", "my-filename", + ssec=SseCustomerKey(b"32byteslongsecretkeymustprovided"), +) +``` + + + +### copy_object(bucket_name, object_name, source, sse=None, metadata=None, tags=None, retention=None, legal_hold=False, metadata_directive=None, tagging_directive=None) + +Create an object by server-side copying data from another object. In this API maximum supported source object size is 5GiB. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:-------------|:----------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `source` | _CopySource_ | Source object information. | +| `sse` | _Sse_ | Server-side encryption of destination object. | +| `metadata` | _dict_ | Any user-defined metadata to be copied along with destination object. | +| `tags` | _Tags_ | Tags for destination object. | +| `retention` | _Retention_ | Retention configuration. | +| `legal_hold` | _bool_ | Flag to set legal hold for destination object. | +| `metadata_directive` | _str_ | Directive used to handle user metadata for destination object. | +| `tagging_directive` | _str_ | Directive used to handle tags for destination object. | + + +__Return Value__ + +| Return | +|:----------------------------| +| _ObjectWriteResult_ object. | + +__Example__ + +```py +from datetime import datetime, timezone +from minio.commonconfig import REPLACE, CopySource + +# copy an object from a bucket to another. +result = client.copy_object( + "my-bucket", + "my-object", + CopySource("my-sourcebucket", "my-sourceobject"), +) +print(result.object_name, result.version_id) + +# copy an object with condition. +result = client.copy_object( + "my-bucket", + "my-object", + CopySource( + "my-sourcebucket", + "my-sourceobject", + modified_since=datetime(2014, 4, 1, tzinfo=timezone.utc), + ), +) +print(result.object_name, result.version_id) + +# copy an object from a bucket with replacing metadata. +metadata = {"test_meta_key": "test_meta_value"} +result = client.copy_object( + "my-bucket", + "my-object", + CopySource("my-sourcebucket", "my-sourceobject"), + metadata=metadata, + metadata_directive=REPLACE, +) +print(result.object_name, result.version_id) +``` + + + +### compose_object(bucket_name, object_name, sources, sse=None, metadata=None, tags=None, retention=None, legal_hold=False) + +Create an object by combining data from different source objects using server-side copy. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------------|:----------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `sources` | _list_ | List of _ComposeSource_ object. | +| `sse` | _Sse_ | Server-side encryption of destination object. | +| `metadata` | _dict_ | Any user-defined metadata to be copied along with destination object. | +| `tags` | _Tags_ | Tags for destination object. | +| `retention` | _Retention_ | Retention configuration. | +| `legal_hold` | _bool_ | Flag to set legal hold for destination object. | + + +__Return Value__ + +| Return | +|:----------------------------| +| _ObjectWriteResult_ object. | + +__Example__ + +```py +from minio.commonconfig import ComposeSource +from minio.sse import SseS3 + +sources = [ + ComposeSource("my-job-bucket", "my-object-part-one"), + ComposeSource("my-job-bucket", "my-object-part-two"), + ComposeSource("my-job-bucket", "my-object-part-three"), +] + +# Create my-bucket/my-object by combining source object +# list. +result = client.compose_object("my-bucket", "my-object", sources) +print(result.object_name, result.version_id) + +# Create my-bucket/my-object with user metadata by combining +# source object list. +result = client.compose_object( + "my-bucket", + "my-object", + sources, + metadata={"test_meta_key": "test_meta_value"}, +) +print(result.object_name, result.version_id) + +# Create my-bucket/my-object with user metadata and +# server-side encryption by combining source object list. +client.compose_object("my-bucket", "my-object", sources, sse=SseS3()) +print(result.object_name, result.version_id) +``` + + + +### put_object(bucket_name, object_name, data, length, content_type="application/octet-stream", metadata=None, sse=None, progress=None, part_size=0, num_parallel_uploads=3, tags=None, retention=None, legal_hold=False) + +Uploads data from a stream to an object in a bucket. + +__Parameters__ + +| Param | Type | Description | +|:---------------|:------------|:--------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `data` | _object_ | An object having callable read() returning bytes object. | +| `length` | _int_ | Data size; -1 for unknown size and set valid part_size. | +| `content_type` | _str_ | Content type of the object. | +| `metadata` | _dict_ | Any additional metadata to be uploaded along with your PUT request. | +| `sse` | _Sse_ | Server-side encryption. | +| `progress` | _threading_ | A progress object. | +| `part_size` | _int_ | Multipart part size. | +| `tags` | _Tags_ | Tags for the object. | +| `retention` | _Retention_ | Retention configuration. | +| `legal_hold` | _bool_ | Flag to set legal hold for the object. | + +__Return Value__ + +| Return | +|:----------------------------| +| _ObjectWriteResult_ object. | + +__Example__ +```py +# Upload data. +result = client.put_object( + "my-bucket", "my-object", io.BytesIO(b"hello"), 5, +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload unknown sized data. +data = urlopen( + "https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.4.81.tar.xz", +) +result = client.put_object( + "my-bucket", "my-object", data, length=-1, part_size=10*1024*1024, +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with content-type. +result = client.put_object( + "my-bucket", "my-object", io.BytesIO(b"hello"), 5, + content_type="application/csv", +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with metadata. +result = client.put_object( + "my-bucket", "my-object", io.BytesIO(b"hello"), 5, + metadata={"My-Project": "one"}, +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with customer key type of server-side encryption. +result = client.put_object( + "my-bucket", "my-object", io.BytesIO(b"hello"), 5, + sse=SseCustomerKey(b"32byteslongsecretkeymustprovided"), +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with KMS type of server-side encryption. +result = client.put_object( + "my-bucket", "my-object", io.BytesIO(b"hello"), 5, + sse=SseKMS("KMS-KEY-ID", {"Key1": "Value1", "Key2": "Value2"}), +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with S3 type of server-side encryption. +result = client.put_object( + "my-bucket", "my-object", io.BytesIO(b"hello"), 5, + sse=SseS3(), +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with tags, retention and legal-hold. +date = datetime.utcnow().replace( + hour=0, minute=0, second=0, microsecond=0, +) + timedelta(days=30) +tags = Tags(for_object=True) +tags["User"] = "jsmith" +result = client.put_object( + "my-bucket", "my-object", io.BytesIO(b"hello"), 5, + tags=tags, + retention=Retention(GOVERNANCE, date), + legal_hold=True, +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with progress bar. +result = client.put_object( + "my-bucket", "my-object", io.BytesIO(b"hello"), 5, + progress=Progress(), +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) +``` + + + +### fput_object(bucket_name, object_name, file_path, content_type="application/octet-stream", metadata=None, sse=None, progress=None, part_size=0, num_parallel_uploads=3, tags=None, retention=None, legal_hold=False) + +Uploads data from a file to an object in a bucket. + +| Param | Type | Description | +|:---------------|:------------|:--------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `file_path` | _str_ | Name of file to upload. | +| `content_type` | _str_ | Content type of the object. | +| `metadata` | _dict_ | Any additional metadata to be uploaded along with your PUT request. | +| `sse` | _Sse_ | Server-side encryption. | +| `progress` | _threading_ | A progress object. | +| `part_size` | _int_ | Multipart part size. | +| `tags` | _Tags_ | Tags for the object. | +| `retention` | _Retention_ | Retention configuration. | +| `legal_hold` | _bool_ | Flag to set legal hold for the object. | + +__Return Value__ + +| Return | +|:----------------------------| +| _ObjectWriteResult_ object. | + +__Example__ + +```py +# Upload data. +result = client.fput_object( + "my-bucket", "my-object", "my-filename", +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with content-type. +result = client.fput_object( + "my-bucket", "my-object", "my-filename", + content_type="application/csv", +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with metadata. +result = client.fput_object( + "my-bucket", "my-object", "my-filename", + metadata={"My-Project": "one"}, +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with customer key type of server-side encryption. +result = client.fput_object( + "my-bucket", "my-object", "my-filename", + sse=SseCustomerKey(b"32byteslongsecretkeymustprovided"), +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with KMS type of server-side encryption. +result = client.fput_object( + "my-bucket", "my-object", "my-filename", + sse=SseKMS("KMS-KEY-ID", {"Key1": "Value1", "Key2": "Value2"}), +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with S3 type of server-side encryption. +result = client.fput_object( + "my-bucket", "my-object", "my-filename", + sse=SseS3(), +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with tags, retention and legal-hold. +date = datetime.utcnow().replace( + hour=0, minute=0, second=0, microsecond=0, +) + timedelta(days=30) +tags = Tags(for_object=True) +tags["User"] = "jsmith" +result = client.fput_object( + "my-bucket", "my-object", "my-filename", + tags=tags, + retention=Retention(GOVERNANCE, date), + legal_hold=True, +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) + +# Upload data with progress bar. +result = client.fput_object( + "my-bucket", "my-object", "my-filename", + progress=Progress(), +) +print( + "created {0} object; etag: {1}, version-id: {2}".format( + result.object_name, result.etag, result.version_id, + ), +) +``` + + + +### stat_object(bucket_name, object_name, ssec=None, version_id=None, extra_query_params=None) + +Get object information and metadata of an object. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:-----------------|:-------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `ssec` | _SseCustomerKey_ | Server-side encryption customer key. | +| `version_id` | _str_ | Version ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | + +__Return Value__ + +| Return | +|:-------------------------------| +| Object information as _Object_ | + +__Example__ + +```py +# Get object information. +result = client.stat_object("my-bucket", "my-object") +print( + "last-modified: {0}, size: {1}".format( + result.last_modified, result.size, + ), +) + +# Get object information of version-ID. +result = client.stat_object( + "my-bucket", "my-object", + version_id="dfbd25b3-abec-4184-a4e8-5a35a5c1174d", +) +print( + "last-modified: {0}, size: {1}".format( + result.last_modified, result.size, + ), +) + +# Get SSE-C encrypted object information. +result = client.stat_object( + "my-bucket", "my-object", + ssec=SseCustomerKey(b"32byteslongsecretkeymustprovided"), +) +print( + "last-modified: {0}, size: {1}".format( + result.last_modified, result.size, + ), +) +``` + + + +### remove_object(bucket_name, object_name, version_id=None) + +Remove an object. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:---------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `version_id` | _str_ | Version ID of the object. | + +__Example__ + +```py +# Remove object. +client.remove_object("my-bucket", "my-object") + +# Remove version of an object. +client.remove_object( + "my-bucket", "my-object", + version_id="dfbd25b3-abec-4184-a4e8-5a35a5c1174d", +) +``` + + + +### remove_objects(bucket_name, delete_object_list, bypass_governance_mode=False) + +Remove multiple objects. + +__Parameters__ + +| Param | Type | Description | +|:-------------------------|:-----------|:--------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `delete_object_list` | _iterable_ | An iterable containing :class:`DeleteObject ` object. | +| `bypass_governance_mode` | _bool_ | Bypass Governance retention mode. | + +__Return Value__ + +| Return | +|:-----------------------------------------------------------------| +| An iterator containing :class:`DeleteError ` object | + +__Example__ + +```py +# Remove list of objects. +errors = client.remove_objects( + "my-bucket", + [ + DeleteObject("my-object1"), + DeleteObject("my-object2"), + DeleteObject("my-object3", "13f88b18-8dcd-4c83-88f2-8631fdb6250c"), + ], +) +for error in errors: + print("error occured when deleting object", error) + +# Remove a prefix recursively. +delete_object_list = map( + lambda x: DeleteObject(x.object_name), + client.list_objects("my-bucket", "my/prefix/", recursive=True), +) +errors = client.remove_objects("my-bucket", delete_object_list) +for error in errors: + print("error occured when deleting object", error) +``` + + + +### delete_object_tags(bucket_name, object_name, version_id=None) + +Delete tags configuration of an object. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:---------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``object_name`` | _str_ | Object name in the bucket. | +| ``version_id`` | _str_ | Version ID of the object. | + +__Example__ + +```py +client.delete_object_tags("my-bucket", "my-object") +``` + + + +### get_object_tags(bucket_name, object_name, version_id=None) + +Get tags configuration of an object. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:------|:---------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``object_name`` | _str_ | Object name in the bucket. | +| ``version_id`` | _str_ | Version ID of the object. | + +| Return | +|:---------------| +| _Tags_ object. | + +__Example__ + +```py +tags = client.get_object_tags("my-bucket", "my-object") +``` + + + +### set_object_tags(bucket_name, object_name, tags, version_id=None) + +Set tags configuration to an object. + +__Parameters__ + +| Param | Type | Description | +|:----------------|:-------|:---------------------------| +| ``bucket_name`` | _str_ | Name of the bucket. | +| ``object_name`` | _str_ | Object name in the bucket. | +| ``tags`` | _Tags_ | Tags configuration. | +| ``version_id`` | _str_ | Version ID of the object. | + +__Example__ + +```py +tags = Tags.new_object_tags() +tags["Project"] = "Project One" +tags["User"] = "jsmith" +client.set_object_tags("my-bucket", "my-object", tags) +``` + + + +### enable_object_legal_hold(bucket_name, object_name, version_id=None) + +Enable legal hold on an object. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:---------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `version_id` | _str_ | Version ID of the object. | + +__Example__ + +```py +client.enable_object_legal_hold("my-bucket", "my-object") +``` + + + +### disable_object_legal_hold(bucket_name, object_name, version_id=None) + +Disable legal hold on an object. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:---------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `version_id` | _str_ | Version ID of the object. | + +__Example__ + +```py +client.disable_object_legal_hold("my-bucket", "my-object") +``` + + + +### is_object_legal_hold_enabled(bucket_name, object_name, version_id=None) + +Returns true if legal hold is enabled on an object. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------|:---------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `version_id` | _str_ | Version ID of the object. | + +__Example__ + +```py +if client.is_object_legal_hold_enabled("my-bucket", "my-object"): + print("legal hold is enabled on my-object") +else: + print("legal hold is not enabled on my-object") +``` + + + +### get_object_retention(bucket_name, object_name, version_id=None) + +Get retention information of an object. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:-----------------|:-------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `version_id` | _str_ | Version ID of the object. | + +__Return Value__ + +| Return | +|:-------------------| +| _Retention_ object | + + +__Example__ + +```py +config = client.get_object_retention("my-bucket", "my-object") +``` + + + +### set_object_retention(bucket_name, object_name, config, version_id=None) + +Set retention information to an object. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:------------|:---------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `config` | _Retention_ | Retention configuration. | +| `version_id` | _str_ | Version ID of the object. | + +__Example__ + +```py +config = Retention(GOVERNANCE, datetime.utcnow() + timedelta(days=10)) +client.set_object_retention("my-bucket", "my-object", config) +``` + + + +### presigned_get_object(bucket_name, object_name, expires=timedelta(days=7), response_headers=None, request_date=None, version_id=None, extra_query_params=None) + +Get presigned URL of an object to download its data with expiry time and custom request parameters. + +__Parameters__ + +| Param | Type | Description | +|:---------------------|:---------------------|:---------------------------------------------------------------------------------------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `expires` | _datetime.timedelta_ | Expiry in seconds; defaults to 7 days. | +| `response_headers` | _dict_ | Optional response_headers argument to specify response fields like date, size, type of file, data about server, etc. | +| `request_date` | _datetime.datetime_ | Optional request_date argument to specify a different request date. Default is current date. | +| `version_id` | _str_ | Version ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | + +__Return Value__ + +| Return | +|:-----------| +| URL string | + +__Example__ + +```py +# Get presigned URL string to download 'my-object' in +# 'my-bucket' with default expiry (i.e. 7 days). +url = client.presigned_get_object("my-bucket", "my-object") +print(url) + +# Get presigned URL string to download 'my-object' in +# 'my-bucket' with two hours expiry. +url = client.presigned_get_object( + "my-bucket", "my-object", expires=timedelta(hours=2), +) +print(url) +``` + + + +### presigned_put_object(bucket_name, object_name, expires=timedelta(days=7)) + +Get presigned URL of an object to upload data with expiry time and custom request parameters. + +__Parameters__ + +| Param | Type | Description | +|:--------------|:---------------------|:---------------------------------------| +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `expires` | _datetime.timedelta_ | Expiry in seconds; defaults to 7 days. | + +__Return Value__ + +| Return | +|:-----------| +| URL string | + +__Example__ + +```py +# Get presigned URL string to upload data to 'my-object' in +# 'my-bucket' with default expiry (i.e. 7 days). +url = client.presigned_put_object("my-bucket", "my-object") +print(url) + +# Get presigned URL string to upload data to 'my-object' in +# 'my-bucket' with two hours expiry. +url = client.presigned_put_object( + "my-bucket", "my-object", expires=timedelta(hours=2), +) +print(url) +``` + + + +### presigned_post_policy(policy) + +Get form-data of PostPolicy of an object to upload its data using POST method. + +__Parameters__ + +| Param | Type | Description | +|:---------|:-------------|:-------------| +| `policy` | _PostPolicy_ | Post policy. | + +__Return Value__ + +| Return | +|:----------------------------| +| Form-data containing _dict_ | + +__Example__ + +```py +policy = PostPolicy( + "my-bucket", datetime.utcnow() + timedelta(days=10), +) +policy.add_starts_with_condition("key", "my/object/prefix/") +policy.add_content_length_range_condition( + 1*1024*1024, 10*1024*1024, +) +form_data = client.presigned_post_policy(policy) +``` + + + +### get_presigned_url(method, bucket_name, object_name, expires=timedelta(days=7), response_headers=None, request_date=None, version_id=None, extra_query_params=None) + +Get presigned URL of an object for HTTP method, expiry time and custom request parameters. + +__Parameters__ +| Param | Type | Description | +|:---------------------|:---------------------|:---------------------------------------------------------------------------------------------------------------------| +| `method` | _str_ | HTTP method. | +| `bucket_name` | _str_ | Name of the bucket. | +| `object_name` | _str_ | Object name in the bucket. | +| `expires` | _datetime.timedelta_ | Expiry in seconds; defaults to 7 days. | +| `response_headers` | _dict_ | Optional response_headers argument to specify response fields like date, size, type of file, data about server, etc. | +| `request_date` | _datetime.datetime_ | Optional request_date argument to specify a different request date. Default is current date. | +| `version_id` | _str_ | Version ID of the object. | +| `extra_query_params` | _dict_ | Extra query parameters for advanced usage. | + +__Return Value__ + +| Return | +|:-----------| +| URL string | + +__Example__ + +```py +# Get presigned URL string to delete 'my-object' in +# 'my-bucket' with one day expiry. +url = client.get_presigned_url( + "DELETE", + "my-bucket", + "my-object", + expires=timedelta(days=1), +) +print(url) + +# Get presigned URL string to upload 'my-object' in +# 'my-bucket' with response-content-type as application/json +# and one day expiry. +url = client.get_presigned_url( + "PUT", + "my-bucket", + "my-object", + expires=timedelta(days=1), + response_headers={"response-content-type": "application/json"}, +) +print(url) + +# Get presigned URL string to download 'my-object' in +# 'my-bucket' with two hours expiry. +url = client.get_presigned_url( + "GET", + "my-bucket", + "my-object", + expires=timedelta(hours=2), +) +print(url) +``` + +## 5. Explore Further + +- [MinIO Golang Client SDK Quickstart Guide](https://docs.min.io/docs/golang-client-quickstart-guide) +- [MinIO Java Client SDK Quickstart Guide](https://docs.min.io/docs/java-client-quickstart-guide) +- [MinIO JavaScript Client SDK Quickstart Guide](https://docs.min.io/docs/javascript-client-quickstart-guide) diff --git a/source/sdk/python/minio-py.rst b/source/sdk/python/minio-py.rst new file mode 100644 index 00000000..0a9dfcfd --- /dev/null +++ b/source/sdk/python/minio-py.rst @@ -0,0 +1,10 @@ +.. _minio-python: + +.. default-domain:: minio + +.. contents:: Table of Contents + :local: + :depth: 2 + +.. include:: /sdk/python/API.md + :parser: myst_parser.sphinx_ diff --git a/source/security/encryption-overview.rst b/source/security/encryption-overview.rst new file mode 100644 index 00000000..7975897c --- /dev/null +++ b/source/security/encryption-overview.rst @@ -0,0 +1,83 @@ +=========================== +Data and Network Encryption +=========================== + +.. default-domain:: minio + +.. contents:: Table of Contents + :local: + :depth: 2 + +.. |EK| replace:: :abbr:`EK (External Key)` +.. |SSE| replace:: :abbr:`SSE (Server-Side Encryption)` +.. |KMS| replace:: :abbr:`KMS (Key Management System)` + +MinIO supports end-to-end encryption of objects over-the-wire (network +encryption) and on read/write (at-rest). + +Server-Side Object Encryption (SSE) +----------------------------------- + +MinIO supports :ref:`Server-Side Object Encryption (SSE) ` of +objects, where MinIO uses a secret key to encrypt and store objects on disk +(encryption at-rest). + +.. tab-set:: + + .. tab-item:: SSE-KMS (*Recommended*) + :sync: sse-kms + + MinIO supports enabling automatic SSE-KMS encryption of all objects + written to a bucket using a specific External Key (EK) stored on the + external |KMS|. Clients can override the bucket-default |EK| by specifying + an explicit key as part of the write operation. + + For buckets without automatic SSE-KMS encryption, clients can specify + an |EK| as part of the write operation instead. + + SSE-KMS provides more granular and customizable encryption compared to + SSE-S3 and SSE-C and is recommended over the other supported encryption + methods. + + .. tab-item:: SSE-S3 + :sync: sse-s3 + + MinIO supports enabling automatic SSE-S3 encryption of all objects + written to a bucket using an |EK| stored on the external |KMS|. MinIO + SSE-S3 supports *one* |EK| for the entire deployment. + + For buckets without automatic SSE-S3 encryption, clients can request + SSE encryption as part of the write operation instead. + + .. tab-item:: SSE-C + :sync: sse-c + + Clients specify an |EK| as part of the write operation for an object. + MinIO uses the specified |EK| to perform SSE-S3. + + SSE-C does not support bucket-default encryption settings and requires + clients perform all key management operations. + +MinIO SSE requires :ref:`minio-tls`. + +Network Encryption +------------------ + +MinIO supports :ref:`Transport Layer Security (TLS) ` encryption of +incoming and outgoing traffic. MinIO recommends all +MinIO servers run with TLS enabled to ensure end-to-end security of +client-server or server-server transmissions. + +TLS is the successor to Secure Socket Layer (SSL) encryption. SSL is fully +`deprecated `__ as of June 30th, 2018. +MinIO uses only supported (non-deprecated) TLS protocols (TLS 1.2 and later). + +See :ref:`minio-tls` for more complete documentation. + +.. toctree:: + :titlesonly: + :hidden: + + /security/server-side-encryption/minio-server-side-encryption.rst + /security/network-encryption/minio-tls.rst + diff --git a/source/security/security-overview.rst b/source/security/iam-overview.rst similarity index 50% rename from source/security/security-overview.rst rename to source/security/iam-overview.rst index 0aeacf96..31b6eea5 100644 --- a/source/security/security-overview.rst +++ b/source/security/iam-overview.rst @@ -1,6 +1,8 @@ -======== -Security -======== +.. _minio-authentication-and-identity-management: + +============================== +Identity and Access Management +============================== .. default-domain:: minio @@ -8,15 +10,6 @@ Security :local: :depth: 2 -.. |EK| replace:: :abbr:`EK (External Key)` -.. |SSE| replace:: :abbr:`SSE (Server-Side Encryption)` -.. |KMS| replace:: :abbr:`KMS (Key Management System)` - -.. _minio-authentication-and-identity-management: - -Identity and Access Management ------------------------------- - MinIO requires clients authenticate using :s3-api:`AWS Signature Version 4 protocol ` with support for the deprecated Signature Version 2 protocol. Specifically, clients must *authenticate* by @@ -66,71 +59,6 @@ behavior and functionality. Consider deferring to the :iam-docs:`IAM documentation <>` for more complete documentation on IAM, IAM policies, or IAM JSON syntax. -Encryption ----------- - -MinIO supports end-to-end encryption of objects over-the-wire (network -encryption) and on read/write (at-rest). - -Network Encryption -~~~~~~~~~~~~~~~~~~ - -MinIO supports :ref:`Transport Layer Security (TLS) ` encryption of -incoming and outgoing traffic. MinIO recommends all -MinIO servers run with TLS enabled to ensure end-to-end security of -client-server or server-server transmissions. - -TLS is the successor to Secure Socket Layer (SSL) encryption. SSL is fully -`deprecated `__ as of June 30th, 2018. -MinIO uses only supported (non-deprecated) TLS protocols (TLS 1.2 and later). - -See :ref:`minio-tls` for more complete documentation. - -Server-Side Object Encryption (SSE) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -MinIO supports :ref:`Server-Side Object Encryption (SSE) ` of -objects, where MinIO uses a secret key to encrypt and store objects on disk -(encryption at-rest). - -.. tab-set:: - - .. tab-item:: SSE-KMS (*Recommended*) - :sync: sse-kms - - MinIO supports enabling automatic SSE-KMS encryption of all objects - written to a bucket using a specific External Key (EK) stored on the - external |KMS|. Clients can override the bucket-default |EK| by specifying - an explicit key as part of the write operation. - - For buckets without automatic SSE-KMS encryption, clients can specify - an |EK| as part of the write operation instead. - - SSE-KMS provides more granular and customizable encryption compared to - SSE-S3 and SSE-C and is recommended over the other supported encryption - methods. - - .. tab-item:: SSE-S3 - :sync: sse-s3 - - MinIO supports enabling automatic SSE-S3 encryption of all objects - written to a bucket using an |EK| stored on the external |KMS|. MinIO - SSE-S3 supports *one* |EK| for the entire deployment. - - For buckets without automatic SSE-S3 encryption, clients can request - SSE encryption as part of the write operation instead. - - .. tab-item:: SSE-C - :sync: sse-c - - Clients specify an |EK| as part of the write operation for an object. - MinIO uses the specified |EK| to perform SSE-S3. - - SSE-C does not support bucket-default encryption settings and requires - clients perform all key management operations. - -MinIO SSE requires :ref:`minio-tls`. - .. toctree:: :titlesonly: :hidden: @@ -138,6 +66,3 @@ MinIO SSE requires :ref:`minio-tls`. /security/minio-identity-management/basic-authentication-with-minio-identity-provider /security/openid-external-identity-management/external-authentication-with-openid-identity-provider /security/ad-ldap-external-identity-management/external-authentication-with-ad-ldap-identity-provider - /security/server-side-encryption/minio-server-side-encryption.rst - /security/network-encryption/minio-tls.rst -