Create a job using a template

Create a transcoding job based on a predefined job template.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

Before trying this sample, follow the C# setup instructions in the Transcoder API quickstart using client libraries. For more information, see the Transcoder API C# API reference documentation.

To authenticate to Transcoder API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Video.Transcoder.V1;

public class CreateJobFromTemplateSample
{
    public Job CreateJobFromTemplate(
        string projectId, string location, string inputUri, string outputUri, string templateId)
    {
        // Create the client.
        TranscoderServiceClient client = TranscoderServiceClient.Create();

        // Build the parent location name.
        LocationName parent = new LocationName(projectId, location);

        // Build the job.
        Job newJob = new Job
        {
            InputUri = inputUri,
            OutputUri = outputUri,
            TemplateId = templateId
        };

        // Call the API.
        Job job = client.CreateJob(parent, newJob);

        // Return the result.
        return job;
    }
}

Go

Before trying this sample, follow the Go setup instructions in the Transcoder API quickstart using client libraries. For more information, see the Transcoder API Go API reference documentation.

To authenticate to Transcoder API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	transcoder "cloud.google.com/go/video/transcoder/apiv1"
	"cloud.google.com/go/video/transcoder/apiv1/transcoderpb"
)

// createJobFromTemplate creates a job from a template. See
// https://cloud.google.com/transcoder/docs/how-to/jobs#create_jobs_templates
// for more information.
func createJobFromTemplate(w io.Writer, projectID string, location string, inputURI string, outputURI string, templateID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// inputURI := "gs://my-bucket/my-video-file"
	// outputURI := "gs://my-bucket/my-output-folder/"
	// templateID := "my-job-template"
	ctx := context.Background()
	client, err := transcoder.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &transcoderpb.CreateJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Job: &transcoderpb.Job{
			InputUri:  inputURI,
			OutputUri: outputURI,
			JobConfig: &transcoderpb.Job_TemplateId{
				TemplateId: templateID,
			},
		},
	}
	// Creates the job, Jobs take a variable amount of time to run.
	// You can query for the job state.
	response, err := client.CreateJob(ctx, req)
	if err != nil {
		return fmt.Errorf("createJobFromTemplate: %w", err)
	}

	fmt.Fprintf(w, "Job: %v", response.GetName())
	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Transcoder API quickstart using client libraries. For more information, see the Transcoder API Java API reference documentation.

To authenticate to Transcoder API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.cloud.video.transcoder.v1.CreateJobRequest;
import com.google.cloud.video.transcoder.v1.Job;
import com.google.cloud.video.transcoder.v1.LocationName;
import com.google.cloud.video.transcoder.v1.TranscoderServiceClient;
import java.io.IOException;

public class CreateJobFromTemplate {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String location = "us-central1";
    String inputUri = "gs://my-bucket/my-video-file";
    String outputUri = "gs://my-bucket/my-output-folder/";
    String templateId = "my-job-template";

    createJobFromTemplate(projectId, location, inputUri, outputUri, templateId);
  }

  // Creates a job from a job template.
  public static void createJobFromTemplate(
      String projectId, String location, String inputUri, String outputUri, String templateId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) {

      CreateJobRequest createJobRequest =
          CreateJobRequest.newBuilder()
              .setJob(
                  Job.newBuilder()
                      .setInputUri(inputUri)
                      .setOutputUri(outputUri)
                      .setTemplateId(templateId)
                      .build())
              .setParent(LocationName.of(projectId, location).toString())
              .build();

      // Send the job creation request and process the response.
      Job job = transcoderServiceClient.createJob(createJobRequest);
      System.out.println("Job: " + job.getName());
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Transcoder API quickstart using client libraries. For more information, see the Transcoder API Node.js API reference documentation.

To authenticate to Transcoder API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project-id';
// location = 'us-central1';
// inputUri = 'gs://my-bucket/my-video-file';
// outputUri = 'gs://my-bucket/my-output-folder/';
// templateId = 'my-job-template';

// Imports the Transcoder library
const {TranscoderServiceClient} =
  require('@google-cloud/video-transcoder').v1;

// Instantiates a client
const transcoderServiceClient = new TranscoderServiceClient();

async function createJobFromTemplate() {
  // Construct request
  const request = {
    parent: transcoderServiceClient.locationPath(projectId, location),
    job: {
      inputUri: inputUri,
      outputUri: outputUri,
      templateId: templateId,
    },
  };

  // Run request
  const [response] = await transcoderServiceClient.createJob(request);
  console.log(`Job: ${response.name}`);
}

createJobFromTemplate();

PHP

Before trying this sample, follow the PHP setup instructions in the Transcoder API quickstart using client libraries. For more information, see the Transcoder API PHP API reference documentation.

To authenticate to Transcoder API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Video\Transcoder\V1\Client\TranscoderServiceClient;
use Google\Cloud\Video\Transcoder\V1\CreateJobRequest;
use Google\Cloud\Video\Transcoder\V1\Job;

/**
 * Creates a job based on a job template.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 * @param string $location The location of the job.
 * @param string $inputUri Uri of the video in the Cloud Storage bucket.
 * @param string $outputUri Uri of the video output folder in the Cloud Storage bucket.
 * @param string $templateId The job template ID.
 */
function create_job_from_template($projectId, $location, $inputUri, $outputUri, $templateId)
{
    // Instantiate a client.
    $transcoderServiceClient = new TranscoderServiceClient();

    $formattedParent = $transcoderServiceClient->locationName($projectId, $location);
    $job = new Job();
    $job->setInputUri($inputUri);
    $job->setOutputUri($outputUri);
    $job->setTemplateId($templateId);
    $request = (new CreateJobRequest())
        ->setParent($formattedParent)
        ->setJob($job);

    $response = $transcoderServiceClient->createJob($request);

    // Print job name.
    printf('Job: %s' . PHP_EOL, $response->getName());
}

Python

Before trying this sample, follow the Python setup instructions in the Transcoder API quickstart using client libraries. For more information, see the Transcoder API Python API reference documentation.

To authenticate to Transcoder API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import argparse

from google.cloud.video import transcoder_v1
from google.cloud.video.transcoder_v1.services.transcoder_service import (
    TranscoderServiceClient,
)


def create_job_from_template(
    project_id: str,
    location: str,
    input_uri: str,
    output_uri: str,
    template_id: str,
) -> transcoder_v1.types.resources.Job:
    """Creates a job based on a job template.

    Args:
        project_id: The GCP project ID.
        location: The location to start the job in.
        input_uri: Uri of the video in the Cloud Storage bucket.
        output_uri: Uri of the video output folder in the Cloud Storage bucket.
        template_id: The user-defined template ID.

    Returns:
        The job resource.
    """

    client = TranscoderServiceClient()

    parent = f"projects/{project_id}/locations/{location}"
    job = transcoder_v1.types.Job()
    job.input_uri = input_uri
    job.output_uri = output_uri
    job.template_id = template_id

    response = client.create_job(parent=parent, job=job)
    print(f"Job: {response.name}")
    return response

Ruby

Before trying this sample, follow the Ruby setup instructions in the Transcoder API quickstart using client libraries. For more information, see the Transcoder API Ruby API reference documentation.

To authenticate to Transcoder API, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# project_id  = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# location    = "YOUR-JOB-LOCATION"  # (e.g. "us-central1")
# input_uri   = "YOUR-GCS-INPUT-VIDEO"  # (e.g. "gs://my-bucket/my-video-file")
# output_uri  = "YOUR-GCS-OUTPUT-FOLDER/"  # (e.g. "gs://my-bucket/my-output-folder/")
# template_id = "YOUR-JOB-TEMPLATE"  # (e.g. "my-job-template")

# Require the Transcoder client library.
require "google/cloud/video/transcoder"

# Create a Transcoder client.
client = Google::Cloud::Video::Transcoder.transcoder_service

# Build the resource name of the parent.
parent = client.location_path project: project_id, location: location

# Set the job fields.
new_job = {
  input_uri: input_uri,
  output_uri: output_uri,
  template_id: template_id
}

job = client.create_job parent: parent, job: new_job

# Print the job name.
puts "Job: #{job.name}"

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.