Overview

The Media service supports simple media storage that enables you to:

  • Store public files and private files.
  • Manage the file's metadata.
  • Transform image files.
  • Filter media files.

To access a private file, a valid access token is required. It's a very useful feature if you want to store files such as invoices. Public files are accessible without a token. A valid access token is required to list both private and public files though. You can manage public files using the /public/files endpoint, and private files using the /files endpoint.

The Media service stores metadata along with the files. The metadata is a JSON description of your media.

The story

Let’s say you want to build a blog service on YaaS. In your service you want to:

  • Store images scaled for different types of devices.
  • Add media files available only for registered users.
  • Remove any unneeded data automatically.
  • Allow readers to sort files or images by date or relevance.

Here is how the usage of the Media service can help you:

Make images in multiple sizes publicly available

To store image files in multiple sizes and make them publicly available, implement logic to upload and store your images in the Media service. All necessary steps are described in detail in the Manage media topic.

Because you can define multiple image sizes in just one request to the Media service when you upload your images, it is easier and more convenient than ever to implement a scalable interface that includes all image sizes, to fit any device. For more details, see the Transform image files topic. You can also implement logic in your service to automatically transform all image files that you upload. Isn’t it great?

Add media files with restricted access

To store articles in PDF format and selectively make them available only for registered users, use separate endpoints when you upload your files. See the Manage media topic for detailed instructions.

Cleanup

To delete irrelevant data, there are a few options. You can either:

  • Delete a particular file
  • Delete multiple files that meet your custom query criteria
  • Delete all data for a specified user

To create a post with images, implement logic that sends the commit request after the user saves the post. Because the Media service removes all files that have been uploaded, but not committed, within one day, you don't need to worry about orphaned files.

Display a list of media files with options to sort by date and relevance

Thanks to the metadata, you can easily build logic into your services to search for your media files. You can send custom metadata attributes in a POST request. You can also implement logic to list and sort documents using the available options, such as filtering by content type. To explore the filtering options, see the List and filter section of the tutorial.


API Reference

/public

/public/files

get

Returns list of stored files.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_view scope to manage this resource.

post

Creates an upload link for your public media. Given link is temporary.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

delete

Deletes files stored for tenant according to query parameter q. If query parameter q is omitted, then it deletes all files stored for tenant!

Security / Access Control:
To access this method, an access token must be issued for client with the hybris.media_admin scope to manage this resource.

/public/files/{fileId}

get

Returns a direct link to the file stored with the given fileId. The file is being returned as an http redirection using direct link, which is not temporary. By using optional query parameter a link to variant will be returned. Only one variant can be specified.

Security / Access Control:
Does not require an access token.

delete

Deletes the file by the given id.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/public/files/{fileId}/commit

post

Makes your file persistent. If the file is not committed, it will disappear within 1 day. The metadata is optional and can contain an additional information in JSON format.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/public/files/{fileId}/metadata

get

Returns metadata stored with the file.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_view scope to manage this resource.

put

Updates metadata stored with the file by replacing it.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/public/files/{fileId}/variants

get

Returns a list of variants stored for an image file.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_view scope to manage this resource.

post

Adds new variants to a file. You should use clip or crop query parameters to specify variants to be added. At least one variant should be defined.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

delete

Use this endpoint to delete variants. You can use clip or crop query parameters to specify which variants should be removed. You can delete more then one variant. If no variant is specified then all variants will be removed.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/public/bulk/variants

post

Performs bulk image transformation. Either clip, crop or both parameters are required. The overall transformations limit for query is 100. For example, a query pageSize=50&crop=10x10,20x20&clip=10x10 requests 150 transformations, which won't be accepted.



Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

delete

Performs bulk image variants removal. Either clip, crop or both parameters are required.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/files

/files

get

Returns list of stored files for a given tenant.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_view scope to manage this resource.

post

Creates an upload link for your private media. Given link is temporary.

Security / Access Control:
To access this method, access token must be issued for and client and have hybris.media_manage scope to manage this resource.

delete

Deletes files stored for tenant according to query parameter q. If query parameter q is omitted, then it deletes all files stored for tenant!

Security / Access Control:
To access this method, an access token must be issued for client with the hybris.media_admin scope to manage this resource.

/files/{fileId}

get

Returns a temporary link to the file stored with the given fileId. By using optional query parameter a link to variant will be returned. Only one variant can be specified.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_view scope to manage this resource.

delete

Deletes the file by the given id.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/files/{fileId}/commit

post

Makes your file persistent. If the file is not committed, it will disappear within 1 day. The metadata is optional and can contain an additional information in JSON format.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/files/{fileId}/metadata

get

Returns metadata stored with the file.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_view scope to manage this resource.

put

Updates metadata stored with the file by replacing it.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/files/{fileId}/variants

get

Returns a list of variants stored for an image file.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_view scope to manage this resource.

post

Adds new variants to a file. You should use clip or crop query parameters to specify variants to be added. At least one variant should be defined.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

delete

Use this endpoint to delete variants. You can use clip or crop query parameters to specify which variants should be removed. You can delete more then one variant. If no variant is specified then all variants will be removed.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

/bulk/variants

/bulk/variants

post

Performs bulk image transformation. Either clip, crop or both parameters are required. The overall transformations limit for query is 100. For example, a query pageSize=50&crop=10x10,20x20&clip=10x10 requests 150 transformations, which won't be accepted.



Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.

delete

Performs bulk image variants removal. Either clip, crop or both parameters are required.

Security / Access Control:
To access this method, access token must be issued for client and have hybris.media_manage scope to manage this resource.


Considerations

The Media service requires a token obtained with the Client Credentials grant flow to provide an additional level of security. This ensures that users who belong to the project but do not have Client Credentials for any reason, cannot manipulate the project's data and resources. For more information about obtaining an access token and grants, see the OAuth2 service documentation.


Multi tenancy

Core services provide you with multi multi-tenant model, which allows you to manage all your tenants' data in easy and convenient way. Your service is the client of core services, and it may contain as many tenants as you need. Without multi-tenancy, you would have to separate your tenants' data manually. In a multi multi-tenant model, you delegate tenant data separation to core services.

The Media service is a good example of a multi multi-tenant core service as it separates the data for services (clients) and within services for their tenants.

Example:

The Product and the Email services serve multiple tenants to store their documents and media files. Both the Product and the Email service are, in this case, clients of the Document and Media services. The diagram below illustrates those dependencies:

The Media service enables you to manage your service's tenants with a single access token issued for your service. Your service client is the owner of the data, and you don't have to issue new tokens with different hybris.tenant scopes. In the following diagram, two tenants (A and B) call your service. Your service only has to get token once. The same token can then be used for all subsequent requests until the token expires.

sequenceDiagram participant Tenant A participant Tenant B Tenant A->>Your Service: /tenantA/resource Your Service->>OAuth 2.0: /token OAuth 2.0-->>Your Service: token Your Service->>Media: /files/{fileId} with token Media-->>Your Service: response for Tenant A Your Service-->>Tenant A: response for Tenant A Tenant B->>Your Service: /tenantB/resource Your Service->>Media: /files/{fileId} with token Media-->>Your Service: response for Tenant B Your Service-->>Tenant B: response for Tenant B


Security

The Media service is a container for your files. You control the data stored in the Media service, and only you know whether the file contains personal data and which data subject the data relates to. Therefore, to meet the data privacy requirements, you must map files containing personal data to corresponding data subjects, and implement a logic to serve the data subject's requests related to its personal data, such as requests for information or deletion. To meet these goals, follow the instructions provided in the Developer Guidelines for Data Privacy.


Media transformation

The Media service allows you to transform your media files and store different variants of your master file. The following transformations are available:

TransformationDescriptionOriginal imageHow it worksResult image
ClipThe clip transformation operation is designed for image files and resizes the original image to fit within the desired dimensions. The clip transformation keeps the original aspect ratio of an image.
CropThe crop transformation operation resizes image files to fit within the desired dimensions by cutting off the edges of an image.

You can perform bulk media files transformation by performing a POST request on the bulk/variants endpoint. Bulk variants creation supports only image/jpeg, image/gif, and image/png content types, therefore any media files of a different content type are omitted.


Caching

The Media service supports HTTP caching headers to reduce bandwidth, response times, and resources required for processing. The service provides an ETag (entity tag) for every file when you perform a GET request on the /public/files/{fileId} or /files/{fileId} endpoint. The files in the Media service are immutable therefore the ETag is always the same for a given file.

When you perform another GET request on the same file with the If-None-Match header set, along with the correct ETag, which you received in the response of the initial GET request, you receive the 304 Not modified response, without a payload, so that you can use the already cached file. You receive a 200 OK response if the ETag provided in If-None-Match header is incorrect. For example, if you used the ETag for a master file when getting the variant, you receive the 200 OK response. That means you need to get the payload only once for each media file, or its variant, and then use the received ETag to use the cached file.

You can also use ETag validation for variants. After you perform a GET request on the /files/{fileId} or /public/files/{fileId} endpoints with a query on a variant, you receive an ETag for a particular variant. Each variant is a separate media file, and thus each has its own ETag

Example

Initial GET request

GET /public/files/58761eb9bc1eaf3d40b6b12c HTTP/1.1
Host: https://api.beta.yaas.io/hybris/media/v2
Content-Type: application/json

Response containing ETag and Cache-Control headers

HTTP/1.1 302 Found
Cache-Control: no-cache, private
Content-Length: 153
Content-Type: text/html; charset=UTF-8
Date: Wed, 11 Jan 2017 12:13:20 GMT
ETag: "b0b89b2f075beb111ecaed50c6f6a73f"
Location: https://s3.amazonaws.com/sap.yaas.us.stage.public.media/58761eb9bc1eaf3d40b6b12c

Subsequent GET request

GET /public/files/58761eb9bc1eaf3d40b6b12c HTTP/1.1
Host: https://api.beta.yaas.io/hybris/media/v2
Content-Type: application/json
If-None-Match: "b0b89b2f075beb111ecaed50c6f6a73f"

Response based on ETag comparison

HTTP/1.1 304 OK
Cache-Control: no-cache, private
Date: Wed, 11 Jan 2017 12:41:46 GMT
ETag: "b0b89b2f075beb111ecaed50c6f6a73f"


Introduction

In these tutorials, you explore the Media service in detail. Learn how to:

  • Store a public and private media file, and then retrieve it.
  • Manage media with metadata.
  • Sort and filter when listing media files.
  • Transform image files.
  • Delete media files or a specified file.
The following tutorials show how to interact with private media files. To interact with public media, follow the steps below, but use the /public/files endpoint instead.
The API supports all interactions for managing your media files, which you can perform within the service.


Manage Media With Browser

This tutorial presents how to manage media files in the Media service using a browser.

Upload Private Media

First, perform a POST request to the /files endpoint. The Media service returns an upload link. Use this link to upload the media file, and make the POST request to the /files/{fileId}/commit endpoint to store the file permanently.

Fetch Private Media

To fetch private media, make a GET request to the /files/{fileId} endpoint. The response body contains a JSON with a link field. Use this link to load your media in HTML.

Upload Public Media

To upload public media files use the same process, but in this case perform all requests on the /public/files endpoint instead of /files endpoint.

Fetch Public Media

Fetching public media with browser is easy. To display previously uploaded media file, for example, in HTML, provide the file Id and send a GET request:


List and filter

Get all your variables in one place

The following variables are used within this tutorial:

tenant = {{projectId}};
client = {{clientName}};
access_token = {{token}};

Create API client for Media service

API.createClient('mediaService',
'/services/media/v2/api.raml');

The Media service provides you with the functionality to list and filter your media files. You can retrieve filtered media files by querying metadata attributes. This section describes how to use this feature.

The hybris.media_view scope is required to list both private and public media files.

Conditions

and



If you want to list your posted media referring to an attribute or group of attributes, you can use a query built up with key:value pairs separated by spaces. The query implements the and Boolean operator. This limits the search results to those media files that contain the provided attribute value or all of the provided values.

  • This filter does not support other Boolean operators such as or and not.
  • Results are paged. The maximum page size is 1000.

For an example of how to filter your media using a query, see the Tutorials section.

The metadata for your media files is basic key:value data and does not support nested objects. Only strings are supported as key and value.

Values

You can only use string values to filter media using queries. You should put the string value in quotation marks (""). For example:

?q=size:"small"

If your string value contains spaces or special characters, quotation marks ("") are required.:

?q=invoiceType:"pro forma" If a string value does not contain any special characters or spaces, you can omit the quotation marks. For example: ?q=size:small

Sort results

You can sort your results by Content-Type and/or metadata attributes.

Sort by Content-Type

To sort by the type of media, set the sort query parameter to Content-Type.

?sort=Content-Type:asc

The default sort order is ascending, even if you do not put explicit asc in your query:

?sort=Content-Type

To sort in descending order, provide a desc value after the colon. For example:

?sort=Content-Type:desc

Sort by metadata attributes

You can sort results by one or more metadata attributes. To sort your results by one attribute, set the sort query parameter to the name of the attribute.

?sort={key_name}:desc

To provide multiple sort options, separate attributes by commas:

?sort={key_name_1}:desc,{key_name_2}:asc,Content-Type:desc

Retrieve media using a query

To retrieve private media with a query, make a GET request on /files?q={query}, and pass a valid access token with the hybris.media_view scope:

To retrieve public media with a query, a valid access token with the hybris.media_view scope is also required.

Request

To simulate listing the media files filtered by a query you must create sample objects:

media_obj = mediaService.files.post({
  'Content-Type': 'image/jpeg'}, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json'
    }  
  });
  mediaId = media_obj.body.id;
  uploadLink = media_obj.body.uploadLink;
  commitLink = media_obj.body.commitLink;
var file;
loadFile('filePlaceholder', 'readAsArrayBuffer', function(e) {
  file = e.target.result;
});
file
var request = jQuery.ajax({
  url: uploadLink,
  type: 'PUT',
  contentType: 'image/jpeg',
  data: file,
  processData: false,
  async: false
}).done(function(){console.log('uploaded');});
request.status
media_obj = mediaService.files.fileId(mediaId).commit.post(
  {
    'size': 'large'
  }, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json',
    }
  });
media_obj2 = mediaService.files.post({
  'Content-Type': 'image/jpeg'}, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json'
    }      
  });
  mediaId2 = media_obj2.body.id;
  uploadLink2 = media_obj2.body.uploadLink;
  commitLink2 = media_obj2.body.commitLink;
var file2;
loadFile('filePlaceholder2', 'readAsArrayBuffer', function(e) {
  file2 = e.target.result;
});
file2
var request2 = jQuery.ajax({
  url: uploadLink2,
  type: 'PUT',
  contentType: 'image/jpeg',
  data: file,
  processData: false,
  async: false
}).done(function(){console.log('uploaded');});
request2.status
media_obj2 = mediaService.files.fileId(mediaId2).commit.post(
  {
    'size': 'large'
  }, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json',
    }
  });
media_obj3 = mediaService.files.post({
  'Content-Type': 'image/jpeg'}, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json'
    }  
  });
  mediaId3 = media_obj3.body.id;
  uploadLink3 = media_obj3.body.uploadLink;
  commitLink3 = media_obj3.body.commitLink;
var file3;
loadFile('filePlaceholder3', 'readAsArrayBuffer', function(e) {
  file3 = e.target.result;
});
file3
var request3 = jQuery.ajax({
  url: uploadLink3,
  type: 'PUT',
  contentType: 'image/jpeg',
  data: file3,
  processData: false,
  async: false
}).done(function(){console.log('uploaded');});
request3.status
media_obj3 = mediaService.files.fileId(mediaId3).commit.post(
  {
    'size': 'small'
  }, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json',
    }
  });
  • Method: GET
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/
  • Query parameters:
    • Required:
      • tenant: The project that requests this resource. In this example, the tenant is hybris.
    • Optional:
      • q: The query parameter, such as q=invoiceType:"pro forma" size:large
  • Response:
    • Status code: 200
media_obj = mediaService.files.get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  },
  query : {
    'q' : 'size:"large"',
    'tenant' : tenant
  }});
  media_obj.body;

The response contains list of your media files that meet the criteria provided in query. If no files meet the query criteria the response contains empty array.

The list of retrieved media is limited to 1000 items and paged.

Filter media by content type

To retrieve a list of all private media files of a given type, for example all pdf files, perform a GET request on the /files endpoint and specify the type in query parameter content-type. You can pass multiple content types, separating them with a comma.

Request

  • Method: GET
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/
  • Query parameters:
    • Required:
      • tenant: The project that requests this resource. In this example, the tenant is hybris.
    • Optional:
      • content-type: The query, that specifies the content type of a media file, such as application/pdf or image/jpeg. By listing the media files of content type image/jpeg, image/gif, and image/png you receive a list of all media files available for image transformations.
  • Response:
  • Status code: 200
media_obj = mediaService.files.get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  },
  query : {
    'content-type' : 'image/jpeg',
    'tenant' : tenant
  }});
  media_obj.body;

The response contains list of your media files that meet the criteria provided in content-type query parameter. If no files meet such criteria the response contains an empty array.

Use paging and limiting

The Media service uses paging by default, even if the request does not specify it. To support paging, the media service uses a Link HTTP header to provide links to the:

  • Current page: rel=self
  • Previous page:rel=prev (not present if the current page is the first page)
  • Next page: rel=next (not present if the current page is the last page)

You can use the pageSize parameter to specify how many results you want to receive on one page and the pageNumber parameter to point to a specific page of the returned results.

You should always consider limiting the number of returned documents while creating the queries. That helps you to prevent a timeout as a result of too many objects being returned.


Manage media

Get all your variables in one place

The following variables are used within this tutorial:

tenant = {{projectId}};
client = {{clientName}};
access_token = {{token}};

Create API client for Media service

API.createClient('mediaService',
'/services/media/v2/api.raml');

Create media

The Media service enables you to upload private files that are accessible only by you with a valid access token. With this token, you cannot access another tenant's or service's private media. Use it to store sensitive data such as invoices.

Uploading media to the Media service is a three-step process:

  1. Request a temporary upload link for new media.
  2. Upload the file content.
  3. Commit the media file to make it permanent, with optional metadata.

The first step is to create media by performing a POST on the /files endpoint. The request body defines a content type, which is required to upload a file in the next step. If you don't specify the content type in the request body explicitly, it is set to binary/octet-stream by default. You can specify your own content type, for example: application/octet-stream, image/jpeg, audio/mp4, text/plain. Download link sends that information to the browser, so it can render your content properly.

Please remember that multipart/form-data is not supported by Media service v2.
Request
  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files
  • Response:
  • Status code: 200
media_obj = mediaService.files.post({
  'Content-Type': 'image/jpeg'}, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json'
    }
  });

In response you receive a temporary uploadLink, where you should upload your file.

To perform file upload for public/files you need a valid access token with hybris.media_manage scope.
You cannot send chunked files without providing Content-Length header. If you use Transfer-Encoding you must provide exact Content-Length while performing a request.

Assign values to the variable

mediaId = media_obj.body.id;
uploadLink = media_obj.body.uploadLink;
commitLink = media_obj.body.commitLink;

Step 2: Upload the file content

Upload your file by performing a PUT on the uploadLink location. To handle the original file name in the Media service, provide the name of your media file in the Content-Disposition header in this step.

When you retrieve your media file, the system returns the Content-Disposition header along with the response from the Media service, therefore the browser can save your file with the original file name.
Request

The example request below uploads a file. It requires the image/jpeg content type, since it is explicitly specified in the request above:

  • Method: PUT
  • Request URL: https://s3.amazonaws.com/sap.yaas.us.stage.media.temp/507f191e810c19729de860ea?x-amz-security-token=AQoDYXdz...
  • Response:
  • Status code: 200
var file;
loadFile('filePlaceholder', 'readAsArrayBuffer', function(e) {
  file = e.target.result;
});
file
var request = jQuery.ajax({
  url: uploadLink,
  type: 'PUT',
  contentType: 'image/jpeg',
  headers: {"Content-Disposition": 'attachment; filename="frog.png"'},
  data: file,
  processData: false,
  async: false
}).done(function(){console.log('uploaded');});
request.status
When uploading media, make sure you don't have an Authorization header set in the request. The response to PUT with Authorization header is 400 - bad request.

The system temporarily stores your media. If you do not commit the media file, the system removes it within one day.

Step 3: Commit media file

When you make a POST on the /commit, the system finalizes the media file upload. Add optional metadata by defining it as JSON in the request body.

The client which commits the media file becomes the owner and can manage this file exclusively even if different client was used to upload the media file. Even though the tenant query parameter is not required, it is recommended to provide it.
Request
  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{fileId}/commit
  • URI Parameters:
    • Required:
      • fileId: The ID of a file that is committed. In this example, the fileId is 507f191e810c19729de860ea.
  • Query Parameters:
    • Optional:
      • tenant: The tenant which becomes the file owner. In this example, the tenant is mycomicsshop.
  • Response:
  • Status code: 202
media_obj = mediaService.files.fileId(mediaId).commit.post(
  {
    'invoiceType': 'pro-forma'
  }, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json',
    }
  });
  media_obj.body;

After you commit the file, the system stores it permanently.

Retrieve Media

To retrieve private media, make a GET request on /files/{fileId}, and pass a valid access token with the hybris.media_view scope:

Retrieving public media does not require an access token.

Request

  • Method: GET
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{mediaId}
  • URI parameters:
    • Required:
      • mediaID: The unique ID of the media file.
  • Response:
    • Status code: 200
media_obj = mediaService.files.fileId(mediaId).get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  }
});

The response contains a JSON file with a temporary link to your media. Accessing the link you get your media file:

jQuery(parent.document)
.find('#imagePlaceholder')
.attr('src', media_obj.body.link);

With public media, the system responds with an HTTP redirection to your media.

Retrieve metadata information stored for media

Likewise, to retrieve private media's metadata, make a GET request on /files/{fileId}/metadata, and pass a valid access token:

Request

  • Method: GET
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{mediaId}/metadata
  • URI parameters:
    • Required:
      • mediaID: The unique ID of the media file.
  • Response:
    • Status code: 200
media_obj = mediaService.files.fileId(mediaId).metadata.get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  }
})

Update metadata information stored for media

Update your file metadata by performing a PUT on the /files/{mediaId}/metadata.

Request

The example request below updates a file's metadata by replacing the old version with the one you send with this request.

  • Method: PUT
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{mediaId}/metadata
  • URI parameters:
    • Required:
      • mediaID: The unique ID of the media file.
  • Response:
    • Status code: 200
media_obj = mediaService.files.fileId(mediaId).metadata.put({
  'size' : 'large'
}, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  }
})

Delete a media file

To delete a private media file, make a DELETE request on /files/{fileId} endpoint, and pass a valid access token:

Request

  • Method: DELETE
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{mediaId}
  • URI parameters:
    • Required:
      • mediaID: The unique ID of the media file.
  • Response:
  • Status code: 204
media_obj = mediaService.files.fileId(mediaId).delete(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  }
})

Delete multiple media files with a query

To simulate the delete operation, you must create sample media files:

media_obj = mediaService.files.post({
  'Content-Type': 'image/jpeg'}, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json'
    }
  });
  mediaId = media_obj.body.id;
  uploadLink = media_obj.body.uploadLink;
  commitLink = media_obj.body.commitLink;
var file;
loadFile('filePlaceholder', 'readAsArrayBuffer', function(e) {
  file = e.target.result;
});
file
var request = jQuery.ajax({
  url: uploadLink,
  type: 'PUT',
  contentType: 'image/jpeg',
  data: file,
  processData: false,
  async: false
}).done(function(){console.log('uploaded');});
request.status
media_obj = mediaService.files.fileId(mediaId).commit.post(
  {
    'invoiceType': 'pro-forma'
  }, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json',
    }
  });
media_obj2 = mediaService.files.post({
  'Content-Type': 'image/jpeg'}, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json'
    }
  });
  mediaId2 = media_obj2.body.id;
  uploadLink2 = media_obj2.body.uploadLink;
  commitLink2 = media_obj2.body.commitLink;
var file2;
loadFile('filePlaceholder2', 'readAsArrayBuffer', function(e) {
  file2 = e.target.result;
});
file2
var request2 = jQuery.ajax({
  url: uploadLink2,
  type: 'PUT',
  contentType: 'image/jpeg',
  data: file,
  processData: false,
  async: false
}).done(function(){console.log('uploaded');});
request2.status
media_obj2 = mediaService.files.fileId(mediaId2).commit.post(
  {
    'category': 'comics'
  }, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json',
    }
  });

The Media service allows to delete multiple files in a single call by performing a query on metadata attributes. For more information on how to create a query, see the Click me.

The hybris.media_admin scope is required to perform this operation.

Request

  • Method: DELETE
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files?tenant={tenant}&q={key}:{value}
  • Query parameters:
    • Required:
      • tenant: The project for which the delete operation should run.
      • q: The query on the media metadata attributes.
  • Response:
  • Status code: 204
media_obj = mediaService.files.delete(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  },
  query: {
    'q': 'category:comics',
    'tenant': tenant
  }
})
media_obj.status

Get a list of objects with the same query to verify its deletion

Request

  • Method: GET
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/
  • Query parameters:
    • Required:
      • tenant: The project that requests this resource. In this example, the tenant is hybris.
    • Optional:
      • q: The query on the media metadata attributes.
  • Response:
  • Status code: 200
media_obj = mediaService.files.get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  },
  query : {
    'q' : 'category:comics',
    'tenant' : tenant
  }});
  media_obj.body;

Delete all media files stored for a given tenant

To delete private media, make a DELETE request on the /files endpoint, and pass a valid access token.

The hybris.media_admin scope is required to perform this operation.

Request

  • Method: DELETE
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/
  • Query parameters:
    • Required:
      • tenant: The project for which the delete operation should run.
  • Response:
  • Status code: 202
media_obj = mediaService.files.delete(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token
  },
  query: {
    'tenant' : tenant
  }
})
media_obj.status


Transform image files

Get all your variables in one place

The following variables are used within this tutorial:

tenant = {{projectId}};
client = {{clientName}};
access_token = {{token}};

Create API client for Media service

API.createClient('mediaService',
'/services/media/v2/api.raml');

The Media service allows you to transform the original image into another one and store it as a variant. It can be very useful if you want to have your images in different sizes to accommodate different devices.

Currently, the Media service supports two types of transformations:

  • Clip - resizes the original image to fit within the desired dimensions, keeping its aspect ratio.
  • Crop - resizes the original image to fit within the desired dimensions by cutting off the edges.

There are two options to create a variants of your image:

  • You can declare additional image variants while creating an original file.
  • You can request new variants for an exiting file or all files.
You can only transform image media files. The supported content types are: image/jpeg, image/gif, and image/png.

Clip

This operation resizes the original image to fit within the desired dimensions, keeping its aspect ratio. In the body of the request, you must specify the content type of an original image. The supported content types are: image/jpeg, image/gif, or image/png. The query clip should specify maximum values for both image dimensions, for example: 300x300.

  • Method: POST
  • Query parameters:
    • Optional:
      • clip: The parameter that specifies the dimensions of a clip variant. This parameter triggers transformation.
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files

Crop

This operation removes outer parts of the original image to specified dimensions. Same as for clip operation, you must specify the content type of an original image in the body of the request. The supported content types are: image/jpeg, image/gif, or image/png. The query crop should specify maximum values for both image dimensions, for example: 300x300.

Request

  • Method: POST
  • Query parameters:
    • Optional:
      • crop: The parameter that specifies the dimensions of a crop variant. This parameter triggers transformation.
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files

Create variants when uploading an image

You can easily create variants right as you upload an image. In this example we'll create three variants: clip (600x600 and 300x200) and crop (200x200). Note, that it's possible to create multiple variants in just one call.

media_obj = mediaService.files.post({
  'Content-Type': 'image/jpeg'}, {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json'
    },
    query:    {
      'clip': '600x600,300x200',
      'crop': '200x200'
    }
  });
  mediaId = media_obj.body.id;
  uploadLink = media_obj.body.uploadLink;
  commitLink = media_obj.body.commitLink;

Now upload and commit the file in a standard way:

var file;
loadFile('filePlaceholder', 'readAsArrayBuffer', function(e) {
  file = e.target.result;
});
file
var request = jQuery.ajax({
  url: uploadLink,
  type: 'PUT',
  contentType: 'image/jpeg',
  data: file,
  processData: false,
  async: false
});
request.status
media_obj = mediaService.files.fileId(mediaId).commit.post({},
  {
    headers: {
      'Authorization': 'Bearer ' + access_token,
      'Content-Type' : 'application/json',
    }
  });

Please note that variants are created asynchronously, so it might take some time for the image to become available.

Request

  • Method: GET
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{fileId}
    • Query parameters:
      • Optional:
      • clip: The parameter that specifies the dimensions of a clip variant. If not specified, you will retrieve a master image file.
      • crop: The parameter that specifies the dimensions of a crop variant. If not specified, you will retrieve a master image file.
      • fallback: Use this parameter only when you provide either the clip or crop parameter. When the fallback value is true, and the variant requested does not exist, the service returns a master file that contains all variants.
  • Response:
    • Status code: 200

The response contains a JSON file with a temporary link to your media:

With public media, the response is an HTTP redirection to your media.

Get 600x600 clipped variant

get_obj = mediaService.files.fileId(mediaId).get(null,
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    query : {
      'clip': '600x600',
      'tenant' : tenant
    }
  });
  get_obj.body;
jQuery(parent.document)
.find('#imagePlaceholder')
.attr('src', get_obj.body.link);

Get 300x200 clipped variant

get_obj2 = mediaService.files.fileId(mediaId).get(null,
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    query : {
      'clip': '300x200',
      'tenant' : tenant
    }
  });
  get_obj.body;
jQuery(parent.document)
.find('#imagePlaceholder2')
.attr('src', get_obj2.body.link);

Get 200x200 cropped variant

get_obj3 = mediaService.files.fileId(mediaId).get(null,
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    query : {
      'crop': '200x200',
      'tenant' : tenant
    }
  });
  get_obj.body;
jQuery(parent.document)
.find('#imagePlaceholder3')
.attr('src', get_obj3.body.link);

Add variants to an existing image

It's possible to create a variant for an existing image. To do this, perform a POST request on the /files/{fileId}/variants endpoint with a proper query parameter specifying kind of transformation and dimensions.

Request

  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{fileId}/variants
    • Query parameters:
      • Optional:
        • clip: The parameter that specifies the dimensions to which the variant should be resized.
        • crop: The parameter that specifies the dimensions to which the edges of a variant should be cut. At least one transformation parameter is required.
  • Response:
    • Status code: 200
media_obj = mediaService.files.fileId(mediaId).variants.post(null, 
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    query : {
      'crop': '100x100'
    }
  });
  media_obj;

Get list of variants available for an image file

To obtain a list of available variants of your master file, perform a GET request on the /files/{fileId}/variants endpoint.

Request

  • Method: GET
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{fileId}/variants
  • Response:
    • Status code: 200
get_obj = mediaService.files.fileId(mediaId).variants.get(null, 
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    }
  });
  get_obj.body;

Delete specific variants of an image file

To delete only a particular variant of your master file, perform a DELETE request on the /files/{fileId}/variants endpoint with chosen query parameter specifying which variants you want to get rid of. You can specify more than one variant as you did when creating it.

Request

  • Method: DELETE
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{fileId}/variants
    • Query parameters:
      • Optional:
        • clip: The parameter that specifies the dimensions of a clip variant.
        • crop: The parameter that specifies the dimensions of a crop variant.
  • Response:
    • Status code: 204
mediaService.files.fileId(mediaId).variants.delete(null, 
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    query : {
      'crop': '200x200',
      'clip': '300x200'
    }
  });

Now let's make sure that the variants we specified are removed:

get_obj = mediaService.files.fileId(mediaId).variants.get(null, 
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    }
  })
  get_obj.body

Delete all variants of an image file

You can also remove all variants of a given media.

Request

  • Method: DELETE
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/files/{fileId}/variants
  • Response:
    • Status code: 204
mediaService.files.fileId(mediaId).variants.delete(null, 
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    }
  })

Now let's make sure, that all variants are removed:

get_obj = mediaService.files.fileId(mediaId).variants.get(null, 
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    query : {
      'tenant' : tenant
    }
  });
  get_obj.body;

Bulk operations on variants

Add variants to multiple media files

You can trigger bulk variants creation by performing a POST request on the /bulk/variants endpoint. Specify the q query parameter to limit variants creation to the specific image files. You can create 100 variants per request, therefore it is recommended to specify page size and page number in the query parameters. You can also specify the content type of a files to be transformed. The supported content types are image/jpeg, image/png and image/gif.

Request
  • Method: POST
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/bulk/variants
    • Query parameters:
      • Required:
        • tenant: The project that requests this resource.
      • Optional:
        • clip: The parameter that specifies the dimensions to which the variant should be resized.
        • crop: The parameter that specifies the dimensions to which the edges of a variant should be cut. At least one transformation parameter is required.
        • q: The query parameter, such as q=invoiceType:"pro forma" size:large
        • pageSize: The parameter to specify how many results should be returned on one page. The default page size is 16.
        • pageNumber: parameter to point to a specific page of the returned results.
        • content-type: The query, that specifies the content type of a media file, such as image/jpeg.
          If not specified all files of supported types are transformed.
media_obj = mediaService.bulk.variants.post(null, 
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    query : {
      'crop': '100x100',
      'pageNumber' : 1,
      'content-type' : "image/jpeg",
      'tenant' : tenant
    }
  });
  media_obj;

Delete variants of multiple files

To delete variants of multiple image files, perform a DELETE request on the /bulk/variants endpoint. Specify the q query parameter to limit variants creation to the specific image files. You can delete 100 variants per request, therefore it is recommended to specify page size and page number in the query parameters.

Request

  • Method: DELETE
  • Request URL: https://api.beta.yaas.io/hybris/media/v2/bulk/variants

    • Query parameters:
      • Required:
        • tenant:
      • Optional:
        • clip: The parameter that specifies the dimensions to which the variant should be resized.
        • crop: The parameter that specifies the dimensions to which the edges of a variant should be cut. At least one transformation parameter is required.
        • q: The query parameter, such as q=invoiceType:"pro forma" size:large
        • pageSize: The parameter to specify how many results should be returned on one page. The default page size is 16.
        • pageNumber: parameter to point to a specific page of the returned results.
  • Response:

    • Status code: 204
mediaService.bulk.variants.delete(null, 
  {
    headers: {
      'Authorization': 'Bearer ' + access_token
    },
    query : {
      'crop': '100x100',
      'tenant': tenant
    }
  })


Security

The Media service is a container for your files. You control the data stored in the Media service, and only you know whether the file contains personal data and which data subject the data relates to. Therefore, to meet the data privacy requirements, you must map files containing personal data to corresponding data subjects, and implement a logic to serve the data subject's requests related to its personal data, such as requests for information or deletion. To meet these goals, follow the instructions provided in the Developer Guidelines for Data Privacy.


Glossary

TermDescription
mediaAn image, audio, or video file.
metadataMedia file description. In other words, it"s a JSON document, that contains information about the file.
transformationAn operation of creating a new variant from the original media file, such as resize or crop.
variantA new version of an original image file that was created after it had been transformed.


  • Send feedback

    If you find any information that is unclear or incorrect, please let us know so that we can improve the Dev Portal content.

  • Get Help

    Use our private help channel. Receive updates over email and contact our specialists directly.

  • hybris Experts

    If you need more information about this topic, visit hybris Experts to post your own question and interact with our community and experts.