Code Samples

Use the code samples below to integrate your applications with the API.

Node SDK

Submit a local file for transcription

attention

This example uses the Rev AI Node SDK.

The following example demonstrates how to submit a local audio file for transcription.

To use this example, replace the <FILEPATH> placeholder with the path to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
// create a client
import { RevAiApiClient } from 'revai-node-sdk';

var accessToken = '<REVAI_ACCESS_TOKEN>';
var filePath = '<FILEPATH>';

// initialize the client with your access token
var client = new RevAiApiClient(accessToken);

// submit a local file
var job = await client.submitJobLocalFile(filePath);

// retrieve transcript
// as plain text
var transcriptText = await client.getTranscriptText(job.id);

// or as an object
var transcriptObject = await client.getTranscriptObject(job.id);

Submit a remote file for transcription

attention

This example uses the Rev AI Node SDK.

The following example demonstrates how to submit a remote audio file for transcription.

To use this example, replace the <URL> placeholder with the public URL to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
import { RevAiApiClient } from 'revai-node-sdk';

var accessToken = '<REVAI_ACCESS_TOKEN>';
var sourceConfig = {url: '<URL>', auth_headers: null};
const jobOptions = {source_config: sourceConfig}

// initialize the client with your access token
var client = new RevAiApiClient(accessToken);

// submit via a public URL
var job = await client.submitJob(jobOptions);

// retrieve transcript
// as plain text
var transcriptText = await client.getTranscriptText(job.id);

// or as an object
var transcriptObject = await client.getTranscriptObject(job.id);

Submit an audio stream for transcription

attention

This example uses the Rev AI Node SDK.

The following example demonstrates how to submit an audio stream for transcription.

To use this example, replace the <FILEPATH> placeholder with the path to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
import { RevAiApiClient } from 'revai-node-sdk';

var accessToken = '<REVAI_ACCESS_TOKEN>';
var filePath = '<FILEPATH>';

// initialize the client with your access token
var client = new RevAiApiClient(accessToken);

// submit as audio data, the filename is optional
const stream = fs.createReadStream(filePath);
var job = await client.submitJobAudioData(stream, 'file.mp3');

// retrieve transcript
// as plain text
var transcriptText = await client.getTranscriptText(job.id);

// or as an object
var transcriptObject = await client.getTranscriptObject(job.id);

Send email notifications using a webhook

attention

The following example demonstrates how to implement a webhook handler that receives and parses the HTTP POST message from the Rev AI API and sends an email notification using Express and the Twilio SendGrid API client.

To use this example, you must first replace three placeholders:

  • <SENDER_EMAIL_ADDRESS> and <RECIPIENT_EMAIL_ADDRESS> for the sender and recipient email addresses; and
  • <SENDGRID_API_KEY> for the Twilio SendGrid API key.
Copy
Copied
const bodyParser = require('body-parser');
const express = require('express');
const sendgrid = require('@sendgrid/mail');

// Twilio SendGrid API key
const sendgridKey = '<SENDGRID_API_KEY>';
// sender email address
const senderEmail = '<SENDER_EMAIL>';
// recipient email address
const receiverEmail = '<RECEIVER_EMAIL>';

// set API key for SendGrid
sendgrid.setApiKey(sendgridKey);

// create Express application
const app = express();
app.use(bodyParser.json());

// handle requests to webhook endpoint
app.post('/hook', async req => {
  const job = req.body.job;
  console.log(`Received status for job id ${job.id}: ${job.status}`);    

  const message = {
    from: senderEmail,
    to: receiverEmail,
    subject: `Job ${job.id} is COMPLETE`,
    text: job.status === 'transcribed'
        ? `Log in at https://rev.ai/jobs/speech-to-text/ to collect your transcript.`
        : `An error occurred. Log in at https://rev.ai/jobs/speech-to-text/ to view details.`
  };

  try {
    await sendgrid.send(message);
    console.log('Email successfully sent');
  } catch (e) {
    console.error(e);
  }

});

//  start application on port 3000
app.listen(3000, () => {
  console.log('Webhook listening');
})

Save transcripts to MongoDB using a webhook

attention

This example uses the Rev AI Node SDK, the MongoDB Node.js Driver and the Express framework.

The following example demonstrates how to implement a webhook handler that receives and parses the HTTP POST message from the Rev AI API and then makes a subsequent request to the API to retrieve the complete transcript. The handler then saves the received data to a MongoDB database collection as a JSON document.

To use this example, you must replace the <MONGODB_CONNECTION_URI> with the connection URI to your MongoDB database and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
const { RevAiApiClient } = require('revai-node-sdk');
const { MongoClient } = require('mongodb');
const bodyParser = require('body-parser');
const express = require('express');

// MongoDB connection string
const mongodbUri = '<MONGODB_CONNECTION_URI>';

// Rev AI access token
const revAiToken = '<REVAI_ACCESS_TOKEN>';

// create Express application
const app = express();
app.use(bodyParser.json());

// create Mongo client
const mongo = new MongoClient(mongodbUri);
mongo.connect();
const db = mongo.db('mydb');
const transcripts = db.collection('transcripts')

// create Rev AI API client
const revAiClient = new RevAiApiClient(revAiToken);

// handle requests to webhook endpoint
app.post('/hook', async req => {
  const job = req.body.job;
  console.log(`Received status for job id ${job.id}: ${job.status}`);

  if (job.status === 'transcribed') {
    // request transcript
    const transcript = await revAiClient.getTranscriptObject(job.id);
    console.log(`Received transcript for job id ${job.id}`);

    // create MongoDB document
    const doc = {
      job_id: job.id,
      created_on: job.created_on,
      language: job.language,
      status: job.status,
      transcript
    }

    // save document to MongoDB
    try {
      const result = await collection.insertOne(doc);
      console.log(`Saved transcript with document id: ${result.insertedId}`);
    } catch (e) {
      console.error(e);
    }
  }
});

//  start application on port 3000
app.listen(3000, () => {
  console.log('Webhook listening');
})

Identify language for transcription using a webhook

attention

This example uses the Rev AI Node SDK and the Express framework.

The following example demonstrates a webhook handler that receives both language identification and transcription job results from the respective APIs. If the results are successful, it performs the following additional processing:

  • For language identification jobs, it obtains the list of identified languages and the most probable language, and then initiates an asynchronous transcription request that includes this language information.
  • For asynchronous transcription jobs, it obtains the final transcript and prints it to the console.

To use this example, replace the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
const { RevAiApiClient } = require('revai-node-sdk');
const bodyParser = require('body-parser');
const express = require('express');
const axios = require('axios');

const token = '<REVAI_ACCESS_TOKEN>';

// create Axios client
const http = axios.create({
  baseURL: 'https://api.rev.ai/',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
});

// create Rev AI API client
const revAiClient = new RevAiApiClient(token);

const getLanguageIdentificationJobResult = async (jobId) => {
  return await http.get(`languageid/v1beta/jobs/${jobId}/result`,
    { headers: { 'Accept': 'application/vnd.rev.languageid.v1.0+json' } })
    .then(response => response.data)
    .catch(console.error);
};

// create Express application
const app = express();
app.use(bodyParser.json());

// define webhook handler
app.post('/hook', async req => {
  // get job, media URL, callback URL
  const job = req.body.job;
  const fileUrl = job.media_url;
  const callbackUrl = job.callback_url;
  console.log(`Received status for job id ${job.id}: ${job.status}`);

  try {
    switch (job.type) {
      // language job result handler
      case 'language_id':
        if (job.status === 'completed') {
          const languageJobResult = await getLanguageIdentificationJobResult(job.id);
          // retrieve most probable language
          // use as input to transcription request
          const languageId = languageJobResult.top_language;
          console.log(`Received result for job id ${job.id}: language '${languageId}'`);
          const transcriptJobSubmission = await revAiClient.submitJobUrl(fileUrl, {
            language: languageId,
            callback_url: callbackUrl
          });
          console.log(`Submitted for transcription with job id ${transcriptJobSubmission.id}`);
        }
        break;
      // transcription job result handler
      case 'async':
        if (job.status === 'transcribed') {
          // retrieve transcript
          const transcriptJobResult = await revAiClient.getTranscriptObject(job.id);
          console.log(`Received transcript for job id ${job.id}`);
          // do something with transcript
          // for example: print to console
          console.log(transcriptJobResult);
        }
        break;
    }
  } catch (e) {
    console.error(e);
  }
});


//  start application on port 3000
app.listen(3000, () => {
  console.log('Webhook listening');
})

Python SDK

Submit a local file for transcription

attention

This example uses the Rev AI Python SDK.

The following example demonstrates how to submit a local audio file for transcription.

To use this example, replace the <FILEPATH> placeholder with the path to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
from rev_ai import apiclient

token = "<REVAI_ACCESS_TOKEN>"
filePath = "<FILEPATH>"

# create your client
client = apiclient.RevAiAPIClient(token)

# send a local file
job = client.submit_job_local_file(filePath)

# check job status
job_details = client.get_job_details(job.id)

# retrieve transcript as text
transcript_text = client.get_transcript_text(job.id)

# retrieve transcript as JSON
transcript_json = client.get_transcript_json(job.id)

# retrieve transcript as a Python object
transcript_object = client.get_transcript_object(job.id)

Submit a remote file for transcription

attention

This example uses the Rev AI Python SDK.

The following example demonstrates how to submit a remote audio file for transcription.

To use this example, replace the <URL> placeholder with the public URL to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
from rev_ai import apiclient

token = "<REVAI_ACCESS_TOKEN>"
source_url = "<URL>"

# create your client
client = apiclient.RevAiAPIClient(token)

# submit a job with a link to the source file
job = client.submit_job_url(source_config=CustomerUrlData(url=source_url))

# check job status
job_details = client.get_job_details(job.id)

# retrieve transcript as text
transcript_text = client.get_transcript_text(job.id)

# retrieve transcript as json
transcript_json = client.get_transcript_json(job.id)

# retrieve transcript as a python object
transcript_object = client.get_transcript_object(job.id)

Java SDK

Submit a local file for transcription

attention

This example uses the Rev AI Java SDK.

The following example demonstrates how to submit a local audio file for transcription.

To use this example, replace the <FILEPATH> placeholder with the path to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
String accessToken = "<REVAI_ACCESS_TOKEN>";
String localPathToFile = "<FILEPATH>";

// initialize the client with your access token
ApiClient apiClient = new ApiClient(accessToken);

// submit a local file
RevAiJob revAiJob = apiClient.submitJobLocalFile(localPathToFile);

// check job status
RevAiJob newlyRefreshedRevAiJob = apiClient.getJobDetails(revAiJob.getJobId());

// retrieve transcript
// as plain text
String transcriptText = apiClient.getTranscriptText(revAiJob.getJobId());

// or as an object
RevAiTranscript revAiTranscript = apiClient.getTranscriptObject(revAiJob.getJobId());

Submit a remote file for transcription

attention

This example uses the Rev AI Java SDK.

The following example demonstrates how to submit a remote audio file for transcription.

To use this example, replace the <URL> placeholder with the public URL to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
String accessToken = "<REVAI_ACCESS_TOKEN>";
String urlLinkToFile = "<URL>";

// initialize the client with your access token
ApiClient apiClient = new ApiClient(accessToken);

// submit a remote file
RevAiJobOptions revAiJobOptions = new RevAiJobOptions();
revAiJobOptions.setSourceConfig(urlLinkToFile);
RevAiJob revAiJob = apiClient.submitJobUrl(revAiJobOptions);

// check job status
RevAiJob newlyRefreshedRevAiJob = apiClient.getJobDetails(revAiJob.getJobId());

// retrieve transcript
// as plain text
String transcriptText = apiClient.getTranscriptText(revAiJob.getJobId());

// or as an object
RevAiTranscript revAiTranscript = apiClient.getTranscriptObject(revAiJob.getJobId());
attention

This example uses the Rev AI Java SDK.

Submit an audio stream for transcription

The following example demonstrates how to submit an audio stream for transcription.

To use this example, replace the <FILEPATH> placeholder with the path to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
String accessToken = "<REVAI_ACCESS_TOKEN>";
String filePath = "<FILEPATH>";

// initialize the client with your access token
ApiClient apiClient = new ApiClient(accessToken);

// submit from a stream 
File file = new File(filePath);
FileInputStream fileInputStream;
try {
  fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
  throw new RuntimeException("Could not find file [" + file.getName() + "]");
}
RevAiJob revAiJob = apiClient.submitJobLocalFile(fileInputStream, String fileName, RevAiJobOptions options);

// check job status
RevAiJob newlyRefreshedRevAiJob = apiClient.getJobDetails(revAiJob.getJobId());

// retrieve transcript
// as plain text
String transcriptText = apiClient.getTranscriptText(revAiJob.getJobId());

// or as an object
RevAiTranscript revAiTranscript = apiClient.getTranscriptObject(revAiJob.getJobId());

PHP

Submit a local file for transcription

attention

This example uses the Guzzle PHP HTTP client.

The following example demonstrates how to submit a local audio file for transcription.

To use this example, replace the <FILEPATH> placeholder with the path to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
<?php

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

use GuzzleHttp\Client;

$token = '<REVAI_ACCESS_TOKEN>';
$file = '<FILEPATH>';

// create client
$client = new Client([
    'base_uri' => 'https://api.rev.ai/speechtotext/v1/',
    'headers' => ['Authorization' => "Bearer $token"]
]);

// send POST request and get response body
$response = $client->request(
    'POST',
    'jobs',
    ['multipart' => [['name' => 'media','contents' => fopen($file, 'r')]]]
)
->getBody()
->getContents();

// decode response JSON and print
print_r(json_decode($response));

Submit a remote file for transcription

attention

This example uses the Guzzle PHP HTTP client.

The following example demonstrates how to submit a remote audio file for transcription.

To use this example, replace the <URL> placeholder with the public URL to the file you wish to transcribe and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
<?php

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

use GuzzleHttp\Client;

$token = '<REVAI_ACCESS_TOKEN>';
$fileUrl = '<URL>';

// create client
$client = new Client([
    'base_uri' => 'https://api.rev.ai/speechtotext/v1/',
    'headers' => ['Authorization' => "Bearer $token"]
]);

// send POST request and get response body
$response = $client->request(
    'POST',
    'jobs',
    ['json' => ['source_config' => ['url' => $fileUrl]]]
)
->getBody()
->getContents();

// decode response JSON and print
print_r(json_decode($response));

Check transcription status

attention

This example uses the Guzzle PHP HTTP client.

The following example demonstrates how to check the status of an asynchronous transcription job.

To use this example, replace the <ID> placeholder with the job identifier and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
<?php

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

use GuzzleHttp\Client;

$token = '<REVAI_ACCESS_TOKEN>';
$jobId = '<ID>';

// create client
$client = new Client([
  'base_uri' => 'https://api.rev.ai/speechtotext/v1/',
  'headers' => ['Authorization' => "Bearer $token"]
]);

// send GET request and get response body
$response = $client->request(
    'GET',
    "jobs/$jobId"
)
->getBody()
->getContents();

// decode response JSON and print
print_r(json_decode($response));

Retrieve a transcript

attention

This example uses the Guzzle PHP HTTP client.

The following example demonstrates how to retrieve the results of an asynchronous transcription job.

To use this example, replace the <ID> placeholder with the job identifier and the <REVAI_ACCESS_TOKEN> placeholder with your Rev AI account's access token.

Copy
Copied
<?php

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

use GuzzleHttp\Client;

$token = '<REVAI_ACCESS_TOKEN>';
$jobId = '<ID>';

// create client
$client = new Client([
    'base_uri' => 'https://api.rev.ai/speechtotext/v1/',
    'headers' => ['Authorization' => "Bearer $token"]
]);

// send GET request and get response body
$response = $client->request(
    'GET',
    "jobs/$jobId/transcript",
    ['headers' => ['Accept' => 'application/vnd.rev.transcript.v1.0+json']]
)
->getBody()
->getContents();

// decode response JSON and print
print_r(json_decode($response));