Hide
Cloud Storage

Objects: insert

Stores a new object and metadata. For tips on uploading to Google Cloud Storage, see best practices. Try it now or see an example.

This method supports an /upload URI and accepts uploaded media with the following characteristics:

  • Maximum file size: 5 TB
  • Accepted Media MIME types: */*

The authenticated user must have WRITER permissions on the bucket.

Note: Despite the note below, metadata-only requests are not allowed; please use only the Upload URI. To change an object's metadata, use either the update or patch methods.

Request

HTTP request

This method provides media upload functionality through two separate URIs. For more details, see the document on media upload.

  • Upload URI, for media upload requests:
    POST https://www.googleapis.com/upload/storage/v1/b/bucket/o
  • Metadata URI, for metadata-only requests:
    POST https://www.googleapis.com/storage/v1/b/bucket/o

Parameters

Parameter name Value Description
Path parameters
bucket string Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
Required query parameters
uploadType string The type of upload request to the /upload URI. Acceptable values are:
  • media - Simple upload. Upload the media only, without any metadata.
  • multipart - Multipart upload. Upload both the media and its metadata, in a single request.
  • resumable - Resumable upload. Upload the file in a resumable fashion, using a series of at least two requests where the first request includes the metadata.
Optional query parameters
contentEncoding string If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded.
ifGenerationMatch long Makes the operation conditional on whether the object's current generation matches the given value.
ifGenerationNotMatch long Makes the operation conditional on whether the object's current generation does not match the given value.
ifMetagenerationMatch long Makes the operation conditional on whether the object's current metageneration matches the given value.
ifMetagenerationNotMatch long Makes the operation conditional on whether the object's current metageneration does not match the given value.
name string Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.
predefinedAcl string Apply a predefined set of access controls to this object.

Acceptable values are:
  • "authenticatedRead": Object owner gets OWNER access, and allAuthenticatedUsers get READER access.
  • "bucketOwnerFullControl": Object owner gets OWNER access, and project team owners get OWNER access.
  • "bucketOwnerRead": Object owner gets OWNER access, and project team owners get READER access.
  • "private": Object owner gets OWNER access.
  • "projectPrivate": Object owner gets OWNER access, and project team members get access according to their roles.
  • "publicRead": Object owner gets OWNER access, and allUsers get READER access.
projection string Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.

Acceptable values are:
  • "full": Include all properties.
  • "noAcl": Omit the acl property.

Request body

In the request body, supply an object resource with the following properties as the metadata. For more information, see the document on media upload.

Property name Value Description Notes
Required Properties
contentType string Content-Type of the object data. writable
Optional Properties
acl[] list Access controls on the object. writable
cacheControl string Cache-Control directive for the object data. writable
contentDisposition string Content-Disposition of the object data. writable
contentEncoding string Content-Encoding of the object data. writable
contentLanguage string Content-Language of the object data. writable
crc32c string CRC32c checksum, as described in RFC 4960, Appendix B; encoded using base64 in big-endian byte order. For more information about using the CRC32c checksum, see Hashes and ETags: Best Practices. writable
md5Hash string MD5 hash of the data; encoded using base64. For more information about using the MD5 hash, see Hashes and ETags: Best Practices. writable
metadata object User-provided metadata, in key/value pairs. writable
metadata.(key) string An individual metadata entry. writable
name string The name of this object. Required if not specified by URL parameter. writable

Response

By default, this responds with an object resource in the response body. If you provide the URL parameter alt=media, then it will respond with the object data in the response body.

Examples

Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).

Java

Uses the Java client library.

// Given
InputStream inputStream;  // object data, e.g., FileInputStream
long byteCount;  // size of input stream

InputStreamContent mediaContent = new InputStreamContent("application/octet-stream", inputStream);
// Knowing the stream length allows server-side optimization, and client-side progress
// reporting with a MediaHttpUploaderProgressListener.
mediaContent.setLength(byteCount);

StorageObject objectMetadata = null;

if (useCustomMetadata) {
  // If you have custom settings for metadata on the object you want to set
  // then you can allocate a StorageObject and set the values here. You can
  // leave out setBucket(), since the bucket is in the insert command's
  // parameters.
  objectMetadata = new StorageObject()
      .setName("myobject")
      .setMetadata(ImmutableMap.of("key1", "value1", "key2", "value2"))
      .setAcl(ImmutableList.of(
          new ObjectAccessControl().setEntity("domain-example.com").setRole("READER"),
          new ObjectAccessControl().setEntity("user-administrator@example.com").setRole("OWNER")
          ))
      .setContentDisposition("attachment");
}

Storage.Objects.Insert insertObject = storage.objects().insert("mybucket", objectMetadata,
    mediaContent);

if (!useCustomMetadata) {
  // If you don't provide metadata, you will have specify the object
  // name by parameter. You will probably also want to ensure that your
  // default object ACLs (a bucket property) are set appropriately:
  // https://developers.google.com/storage/docs/json_api/v1/buckets#defaultObjectAcl
  insertObject.setName("myobject");
}

// For small files, you may wish to call setDirectUploadEnabled(true), to
// reduce the number of HTTP requests made to the server.
if (mediaContent.getLength() > 0 && mediaContent.getLength() <= 2 * 1000 * 1000 /* 2MB */) {
  insertObject.getMediaHttpUploader().setDirectUploadEnabled(true);
}

insertObject.execute();

Python

Uses the Python client library.

# The BytesIO object may be replaced with any io.Base instance.
media = http.MediaIoBaseUpload(io.BytesIO('some data'), 'text/plain')
# All object_resource fields here are optional.
object_resource = {
        'metadata': {'my-key': 'my-value'},
        'contentLanguage': 'en',
        'md5Hash': 'HlAhCgICSX+3m8OLat5sNA==',
        'crc32c': 'rPZE1w==',

}
req = client.objects().insert(
        bucket=bucket_name,
        name=object_name,
        body=object_resource,     # optional
        media_body=media)
resp = req.execute()
print json.dumps(resp, indent=2)

Ruby

Uses the Ruby client library.

# Resumable upload
resumable_media = Google::APIClient::UploadIO.new(FILENAME, MIME_TYPE)
resumable_result = client.execute(
  api_method: storage.objects.insert,
  media: resumable_media,
  parameters: {
    uploadType: 'resumable',
    bucket: BUCKET,
    name: OBJECT
  },
  body_object: {contentType: MIME_TYPE}
)
# Does actual upload of file
upload = resumable_result.resumable_upload
if upload.resumable?
  client.execute(upload)
end
puts "\nResumable insert: "
puts "Created object #{upload.parameters['name']}"

Go

Uses the Go client library.

// Insert an object into a bucket.
filename := "FILE_NAME"
file, err := os.Open(filename)
if err != nil {
	fmt.Printf("error opening %q: %v", filename, err)
}
result, err := service.Objects.Insert("BUCKET_NAME",
	&storage.Object{Name: filename}).Media(file).Do()
fmt.Printf("\nCreated object %v at location %v",
	result.Name, result.SelfLink)

Try it!

Note: APIs Explorer currently supports metadata requests only.

Use the APIs Explorer below to call this method on live data and see the response. Alternatively, try the standalone Explorer.