Using Custom Headers with SDKs

Learn how to use custom headers with the Deepgram SDKs.

JS SDK

The JS SDK provides the ability to set custom headers. This is optional and is only needed when a specific need arises.

Example

const { createClient } = require("../../dist/main/index");
const fs = require("fs");
const path = require("path");

const transcribeUrl = async () => {
  const client = createClient("YOUR DEEPGRAM API KEY", {
    global: {
      fetch: { options: { headers: { "custom_header": "header_value" } } },
    },
  });

  console.log("Transcribing URL", "https://dpgr.am/spacewalk.wav");
  const { result, error } = await deepgram.listen.prerecorded.transcribeUrl(
    {
      url: "https://dpgr.am/spacewalk.wav",
    },
    {
      model: "nova-2",
    }
  );

  if (error) console.error(error);
  if (!error) console.dir(result, { depth: 1 });
};

transcribeUrl();

Python SDK

The Python SDK provides the ability to set custom headers. This is optional and is only needed when a specific need arises.

Example

# Install the SDK: pip install deepgram-sdk

import os
from dotenv import load_dotenv

from deepgram import DeepgramClient, PrerecordedOptions

load_dotenv()

AUDIO_URL = {
    "url": "https://dpgr.am/bueller.wav"
}

def main():
    options: PrerecordedOptions = PrerecordedOptions(
        model="nova-2"
    )

    # To demonstrate using the custom headers parameters, you could enable it like this
    custom_headers: dict = {"custom_header": "header_value"}

    # STEP 1 Create a Deepgram client using the API key in the environment variables DEEPGRAM_API_KEY
    deepgram: DeepgramClient = DeepgramClient()

    try:
        # STEP 2 Call the transcribe_url method on the prerecorded class
        response = deepgram.listen.rest.v("1").transcribe_url(
            AUDIO_URL, options, headers=custom_headers
        )
        print(response.to_json(indent=4))
    except Exception as e:
        print(f"Exception: {e}")

if __name__ == "__main__":
    main()
# Install the SDK: pip install deepgram-sdk

import asyncio
import os
from dotenv import load_dotenv

from deepgram import DeepgramClient, PrerecordedOptions

load_dotenv()

AUDIO_URL = {
    "url": "https://dpgr.am/bueller.wav"
}

async def main():
    options: PrerecordedOptions = PrerecordedOptions(
        model="nova-2",
    )

    # To demonstrate using the custom headers parameters, you could enable it like this
    custom_headers: dict = {"custom_header": "option"}

    # STEP 1 Create a Deepgram client using the API key in the environment variables DEEPGRAM_API_KEY
    deepgram: DeepgramClient = DeepgramClient()

    try:
        # STEP 2 Call the transcribe_url method on the prerecorded class
        response = await deepgram.listen.asyncrest.v("1").transcribe_url(
            AUDIO_URL, options, headers=custom_headers
        )
        print(response.to_json(indent=4))
    except Exception as e:
        print(f"Exception: {e}")

if __name__ == "__main__":
    asyncio.run(main())

.NET SDK

The .NET SDK provides the ability to set custom headers. This is optional and is only needed when a specific need arises.

Example

//Install the SDK: dotnet add package Deepgram

using Deepgram.Models.Listen.v1.REST;

namespace PreRecorded
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Initialize Library with default logging
            // Normal logging is "Info" level
            Library.Initialize();

            // Set "DEEPGRAM_API_KEY" environment variable to your Deepgram API Key
            var deepgramClient = ClientFactory.CreateListenRESTClient();
          
            var prerecordedOptions = new PreRecordedSchema()
            {
                Model = "nova-2"
            };
          
            // but to demonstrate using the custom headers, you could enable it like this
            var customHeaders = new Dictionary<string, string>();
            customHeaders["custom_header"] = "header_value";

            var response = await deepgramClient.TranscribeUrl(
                new UrlSource("https://dpgr.am/bueller.wav"),
                prerecordedOptions,
                null, // Don't want to specify a cancellation token, use the default
                null, // Placeholder for custom query parameters
                customHeaders,
            	);

            Console.WriteLine(response);

            // Teardown Library
            Library.Terminate();
        }
    }
}

Go SDK

The Go SDK provides the ability to set custom headers. This is optional and is only needed when a specific need arises.

Example

// Install the SDK: go get github.com/deepgram/deepgram-go-sdk

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	prettyjson "github.com/hokaccha/go-prettyjson"

	api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest"
	interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces"
	client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen"
)

const (
	url string = "https://dpgr.am/bueller.wav"
)

func main() {
	// init library
	client.InitWithDefault()

	// Go context
	ctx := context.Background()

	// set the Transcription options
	options := &interfaces.PreRecordedTranscriptionOptions{
		Model: "nova-2",
	}

	// create a Deepgram client
	c := client.NewRESTWithDefaults()
	dg := api.New(c)

	// but to demonstrate using the custom headers, you could enable it like this
	headers := http.Header{}
	headers.Add("custom_header", "header_value")
	ctx = interfaces.WithCustomHeaders(ctx, headers)

	// send/process file to Deepgram
	res, err := dg.FromURL(ctx, url, options)
	if err != nil {
		if e, ok := err.(*interfaces.StatusError); ok {
			fmt.Printf("DEEPGRAM ERROR:\n%s:\n%s\n", e.DeepgramError.ErrCode, e.DeepgramError.ErrMsg)
		}
		fmt.Printf("FromStream failed. Err: %v\n", err)
		os.Exit(1)
	}

	data, err := json.Marshal(res)
	if err != nil {
		fmt.Printf("json.Marshal failed. Err: %v\n", err)
		os.Exit(1)
	}

	// make the JSON pretty
	prettyJSON, err := prettyjson.Format(data)
	if err != nil {
		fmt.Printf("prettyjson.Marshal failed. Err: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("\n\nResult:\n%s\n\n", prettyJSON)
}