SDK quick start

Updated at:

OSS SDKs for Java, Python, Go, PHP, C#, and Node.js connect applications to buckets and support object upload, download, and deletion. Use this quick start to configure an SDK and verify OSS access.

Prerequisites

  1. OSS is activated and a bucket is created. For more information, see Console Quick Start.

  2. An AccessKey pair is available. If you do not have an AccessKey pair, see Create an AccessKey pair.

    Important

    To reduce the risk of exposing the AccessKey pair of your Alibaba Cloud account, use the AccessKey pair of a RAM user. Follow the principle of least privilege and grant the RAM user the oss:PutObject, oss:GetObject, and oss:DeleteObject permissions on the test bucket.

Configure access credentials

The SDK reads the AccessKey pair from environment variables. Do not hard-code an AccessKey pair in your code.

macOS or Linux

export OSS_ACCESS_KEY_ID="yourAccessKeyId"
export OSS_ACCESS_KEY_SECRET="yourAccessKeySecret"

Windows PowerShell

$env:OSS_ACCESS_KEY_ID="yourAccessKeyId"
$env:OSS_ACCESS_KEY_SECRET="yourAccessKeySecret"

Prepare the example parameters

Before you run the code, replace the following parameters with your actual values.

Parameter

Example value

Description

region <region-id> The region ID of the bucket.
bucket example-bucket The name of the existing bucket.
key example.txt The full name of the example object. The code deletes this object before it exits.

The Java, Python, Go, PHP, and C# V2 SDKs use the default public endpoint based on the region ID. Therefore, you do not need to explicitly configure an endpoint in this example. For the Node.js SDK, prefix the region ID with oss-. To use an internal endpoint, an acceleration endpoint, or a custom domain name, see Access OSS via Endpoints and Bucket Domains.

SDK examples

Select your programming language. Each tab provides the SDK installation command and complete code for client initialization, upload, download verification, deletion, and resource cleanup.

Java SDK V2

Add the following dependency to the pom.xml file of your Maven project. The example uses version 0.5.1.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alibabacloud-oss-v2</artifactId>
    <version>0.5.1</version>
</dependency>

Example code:

package com.example.oss;

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.models.DeleteObjectRequest;
import com.aliyun.sdk.service.oss2.models.GetObjectRequest;
import com.aliyun.sdk.service.oss2.models.GetObjectResult;
import com.aliyun.sdk.service.oss2.models.PutObjectRequest;
import com.aliyun.sdk.service.oss2.transport.BinaryData;
import com.aliyun.sdk.service.oss2.utils.IOUtils;

import java.nio.charset.StandardCharsets;

public class QuickStart {
    public static void main(String[] args) throws Exception {
        String region = "<region-id>";
        String bucket = "example-bucket";
        String key = "example.txt";
        String content = "Hello OSS";

        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                .region(region)
                .build()) {
            boolean uploaded = false;
            try {
                client.putObject(PutObjectRequest.newBuilder()
                        .bucket(bucket)
                        .key(key)
                        .body(BinaryData.fromString(content))
                        .build());
                uploaded = true;
                System.out.println("Object uploaded");

                String downloaded;
                try (GetObjectResult result = client.getObject(GetObjectRequest.newBuilder()
                        .bucket(bucket)
                        .key(key)
                        .build())) {
                    downloaded = new String(IOUtils.toByteArray(result.body()), StandardCharsets.UTF_8);
                }
                if (!content.equals(downloaded)) {
                    throw new IllegalStateException("Downloaded content does not match uploaded content");
                }
                System.out.println("Downloaded content: " + downloaded);
            } finally {
                if (uploaded) {
                    client.deleteObject(DeleteObjectRequest.newBuilder()
                            .bucket(bucket)
                            .key(key)
                            .build());
                    System.out.println("Object deleted");
                }
            }
        }

        System.out.println("Quick start completed");
    }
}

For more configurations and examples, see OSS Java SDK V2.

Python SDK V2

Install the SDK. The example uses version 1.3.2.

python3 -m pip install alibabacloud-oss-v2

Example code:

import alibabacloud_oss_v2 as oss


def main():
    region = "<region-id>"
    bucket = "example-bucket"
    key = "example.txt"
    content = "Hello OSS"

    config = oss.config.load_default()
    config.credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    config.region = region
    client = oss.Client(config)

    uploaded = False
    try:
        client.put_object(oss.PutObjectRequest(
            bucket=bucket,
            key=key,
            body=content.encode("utf-8"),
        ))
        uploaded = True
        print("Object uploaded")

        result = client.get_object(oss.GetObjectRequest(bucket=bucket, key=key))
        with result.body as body_stream:
            downloaded = body_stream.read().decode("utf-8")
        if downloaded != content:
            raise RuntimeError("Downloaded content does not match uploaded content")
        print(f"Downloaded content: {downloaded}")
    finally:
        if uploaded:
            client.delete_object(oss.DeleteObjectRequest(bucket=bucket, key=key))
            print("Object deleted")

    print("Quick start completed")


if __name__ == "__main__":
    main()

For more configurations and examples, see OSS Python SDK V2.

Go SDK V2

Install the latest SDK version. The example uses v1.5.3.

go get github.com/aliyun/alibabacloud-oss-go-sdk-v2@latest

Example code:

package main

import (
    "context"
    "fmt"
    "io"
    "log"
    "strings"

    "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
    "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

func run() (err error) {
    region := "<region-id>"
    bucket := "example-bucket"
    key := "example.txt"
    content := "Hello OSS"
    ctx := context.Background()

    config := oss.LoadDefaultConfig().
        WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
        WithRegion(region)
    client := oss.NewClient(config)

    uploaded := false
    defer func() {
        if !uploaded {
            return
        }
        _, deleteErr := client.DeleteObject(ctx, &oss.DeleteObjectRequest{
            Bucket: oss.Ptr(bucket),
            Key:    oss.Ptr(key),
        })
        if deleteErr != nil {
            if err == nil {
                err = fmt.Errorf("delete object: %w", deleteErr)
            }
            return
        }
        fmt.Println("Object deleted")
    }()

    _, err = client.PutObject(ctx, &oss.PutObjectRequest{
        Bucket: oss.Ptr(bucket),
        Key:    oss.Ptr(key),
        Body:   strings.NewReader(content),
    })
    if err != nil {
        return fmt.Errorf("upload object: %w", err)
    }
    uploaded = true
    fmt.Println("Object uploaded")

    result, err := client.GetObject(ctx, &oss.GetObjectRequest{
        Bucket: oss.Ptr(bucket),
        Key:    oss.Ptr(key),
    })
    if err != nil {
        return fmt.Errorf("download object: %w", err)
    }
    defer result.Body.Close()

    data, err := io.ReadAll(result.Body)
    if err != nil {
        return fmt.Errorf("read downloaded object: %w", err)
    }
    downloaded := string(data)
    if downloaded != content {
        return fmt.Errorf("downloaded content does not match uploaded content")
    }
    fmt.Printf("Downloaded content: %s\n", downloaded)

    return nil
}

func main() {
    if err := run(); err != nil {
        log.Fatal(err)
    }
    fmt.Println("Quick start completed")
}

For more configurations and examples, see OSS Go SDK V2.

PHP SDK V2

Use Composer to install the SDK. The example uses version 0.4.0.

composer require alibabacloud/oss-v2

Example code:

<?php

require_once __DIR__ . '/vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

$region = '<region-id>';
$bucket = 'example-bucket';
$key = 'example.txt';
$content = 'Hello OSS';

$config = Oss\Config::loadDefault();
$config->setCredentialsProvider(new Oss\Credentials\EnvironmentVariableCredentialsProvider());
$config->setRegion($region);
$client = new Oss\Client($config);

$uploaded = false;
try {
    $putRequest = new Oss\Models\PutObjectRequest($bucket, $key);
    $putRequest->body = Oss\Utils::streamFor($content);
    $client->putObject($putRequest);
    $uploaded = true;
    echo 'Object uploaded' . PHP_EOL;

    $result = $client->getObject(new Oss\Models\GetObjectRequest($bucket, $key));
    $downloaded = $result->body->getContents();
    if ($downloaded !== $content) {
        throw new RuntimeException('Downloaded content does not match uploaded content');
    }
    echo 'Downloaded content: ' . $downloaded . PHP_EOL;
} finally {
    if ($uploaded) {
        $client->deleteObject(new Oss\Models\DeleteObjectRequest($bucket, $key));
        echo 'Object deleted' . PHP_EOL;
    }
}

echo 'Quick start completed' . PHP_EOL;

For more configurations and examples, see OSS PHP SDK V2.

C# SDK V2

Install the SDK. The example uses version 0.2.0.

dotnet add package AlibabaCloud.OSS.V2

Example code:

using System.Text;
using OSS = AlibabaCloud.OSS.V2;

var region = "<region-id>";
var bucket = "example-bucket";
var key = "example.txt";
var content = "Hello OSS";

var config = OSS.Configuration.LoadDefault();
config.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
config.Region = region;

using var client = new OSS.Client(config);
var uploaded = false;
try
{
    await client.PutObjectAsync(new OSS.Models.PutObjectRequest
    {
        Bucket = bucket,
        Key = key,
        Body = new MemoryStream(Encoding.UTF8.GetBytes(content))
    });
    uploaded = true;
    Console.WriteLine("Object uploaded");

    var result = await client.GetObjectAsync(new OSS.Models.GetObjectRequest
    {
        Bucket = bucket,
        Key = key
    });
    using var body = result.Body ?? throw new InvalidOperationException("The response body is empty");
    using var reader = new StreamReader(body, Encoding.UTF8);
    var downloaded = await reader.ReadToEndAsync();
    if (downloaded != content)
    {
        throw new InvalidOperationException("Downloaded content does not match uploaded content");
    }
    Console.WriteLine($"Downloaded content: {downloaded}");
}
finally
{
    if (uploaded)
    {
        await client.DeleteObjectAsync(new OSS.Models.DeleteObjectRequest
        {
            Bucket = bucket,
            Key = key
        });
        Console.WriteLine("Object deleted");
    }
}

Console.WriteLine("Quick start completed");

For more configurations and examples, see OSS C# SDK V2.

Node.js SDK

Install the SDK. The example uses version 6.23.0.

npm install ali-oss

Example code:

const OSS = require('ali-oss');

const region = 'oss-<region-id>';
const bucket = 'example-bucket';
const key = 'example.txt';
const content = 'Hello OSS';

const client = new OSS({
  region,
  bucket,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
});

async function main() {
  let uploaded = false;
  try {
    await client.put(key, Buffer.from(content, 'utf8'));
    uploaded = true;
    console.log('Object uploaded');

    const result = await client.get(key);
    const downloaded = result.content.toString('utf8');
    if (downloaded !== content) {
      throw new Error('Downloaded content does not match uploaded content');
    }
    console.log(`Downloaded content: ${downloaded}`);
  } finally {
    if (uploaded) {
      await client.delete(key);
      console.log('Object deleted');
    }
  }

  console.log('Quick start completed');
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

For more configurations and examples, see OSS Node.js SDK.

View the result

A successful run returns the following output. If an error occurs after the upload, the example still attempts to delete the uploaded object to avoid ongoing storage usage.

Object uploaded
Downloaded content: Hello OSS
Object deleted
Quick start completed

More SDKs