> ## Documentation Index
> Fetch the complete documentation index at: https://hobbyist-e43fa225.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart: Detect the language of text

> Use Azure Language in Foundry Tools to detect the language of text with client libraries, the REST API, or the Microsoft Foundry portal.

export const ZonePivot = ({group, options = [], defaultValue, label = "Choose an experience"}) => {
  const values = options.map(option => option.id);
  const optionKey = options.map(option => `${option.id}:${option.title}`).join("|");
  const [activePivot, setActivePivot] = useState(defaultValue || values[0]);
  const slugify = value => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  const resolvePivot = () => {
    if (typeof window === "undefined") return defaultValue || values[0];
    const params = new URLSearchParams(window.location.search);
    const requested = params.get("pivots");
    if (requested) {
      const requestedIds = requested.split(",").map(value => value.trim()).filter(Boolean);
      const match = requestedIds.find(id => values.includes(id));
      if (match) return match;
    }
    const hash = window.location.hash.replace(/^#/, "");
    if (hash) {
      const match = options.find(option => option.id === hash || slugify(option.title) === hash);
      if (match) return match.id;
    }
    try {
      const stored = window.localStorage.getItem(`foundry-zone-pivot:${group}`);
      if (values.includes(stored)) return stored;
    } catch {
      return defaultValue || values[0];
    }
    return defaultValue || values[0];
  };
  const publishPivotChange = value => {
    if (typeof window === "undefined") return;
    window.dispatchEvent(new CustomEvent("foundry-zone-pivot-change", {
      detail: {
        group,
        value
      }
    }));
  };
  const syncTableOfContents = () => {
    if (typeof window === "undefined") return;
    window.requestAnimationFrame(() => {
      const toc = document.getElementById("table-of-contents-content");
      if (!toc) return;
      const links = Array.from(toc.querySelectorAll('a[href^="#"]'));
      for (const link of links) {
        const item = link.closest("li");
        const rawId = link.getAttribute("href")?.slice(1);
        if (!item || !rawId) continue;
        let id = rawId;
        try {
          id = decodeURIComponent(rawId);
        } catch {}
        item.style.display = document.getElementById(id) ? "" : "none";
      }
    });
  };
  useEffect(() => {
    const resolvedPivot = resolvePivot();
    setActivePivot(resolvedPivot);
    publishPivotChange(resolvedPivot);
    window.setTimeout(syncTableOfContents, 0);
  }, [group, defaultValue, values.join("|"), optionKey]);
  const selectPivot = value => {
    setActivePivot(value);
    if (typeof window !== "undefined") {
      try {
        window.localStorage.setItem(`foundry-zone-pivot:${group}`, value);
      } catch {}
      const url = new URL(window.location.href);
      const current = url.searchParams.get("pivots");
      const preserved = current ? current.split(",").map(id => id.trim()).filter(id => id && !values.includes(id)) : [];
      url.searchParams.set("pivots", [...preserved, value].join(","));
      window.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`);
    }
    publishPivotChange(value);
    window.setTimeout(syncTableOfContents, 0);
  };
  if (options.length < 2) return null;
  return <div className="not-prose my-6 border-b border-slate-200 pb-3 dark:border-slate-800">
      <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:text-slate-400">
        {label}
      </div>
      <div className="flex flex-wrap gap-2" role="tablist" aria-label={label}>
        {options.map(option => {
    const selected = option.id === activePivot;
    return <button key={option.id} type="button" role="tab" aria-selected={selected} onClick={() => selectPivot(option.id)} className={`rounded-md border px-3 py-1.5 text-sm font-medium transition ${selected ? "border-slate-900 bg-slate-900 text-white shadow-sm dark:border-slate-100 dark:bg-slate-100 dark:text-slate-950" : "border-slate-200 bg-white text-slate-700 hover:border-slate-400 hover:text-slate-950 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-200 dark:hover:border-slate-500"}`}>
              {option.title}
            </button>;
  })}
      </div>
    </div>;
};

export const ZoneContent = ({group, value, options = [], values = [], defaultValue, children}) => {
  const optionKey = options.map(option => `${option.id}:${option.title}`).join("|");
  const [activePivot, setActivePivot] = useState(defaultValue || values[0]);
  const slugify = value => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  const resolvePivot = () => {
    if (typeof window === "undefined") return defaultValue || values[0];
    const params = new URLSearchParams(window.location.search);
    const requested = params.get("pivots");
    if (requested) {
      const requestedIds = requested.split(",").map(value => value.trim()).filter(Boolean);
      const match = requestedIds.find(id => values.includes(id));
      if (match) return match;
    }
    const hash = window.location.hash.replace(/^#/, "");
    if (hash) {
      const match = options.find(option => option.id === hash || slugify(option.title) === hash);
      if (match) return match.id;
    }
    try {
      const stored = window.localStorage.getItem(`foundry-zone-pivot:${group}`);
      if (values.includes(stored)) return stored;
    } catch {
      return defaultValue || values[0];
    }
    return defaultValue || values[0];
  };
  useEffect(() => {
    setActivePivot(resolvePivot());
  }, [group, defaultValue, values.join("|"), optionKey]);
  useEffect(() => {
    const onPivotChange = event => {
      if (event.detail?.group === group && values.includes(event.detail.value)) {
        setActivePivot(event.detail.value);
      }
    };
    window.addEventListener("foundry-zone-pivot-change", onPivotChange);
    return () => window.removeEventListener("foundry-zone-pivot-change", onPivotChange);
  }, [group, values.join("|")]);
  if (activePivot !== value) return null;
  return <>{children}</>;
};

In this quickstart, you use the Azure Language in Foundry Tools language detection feature to identify the language of input text. You can get started using your preferred client library, the REST API, or the Microsoft Foundry portal.

If you don't have an Azure subscription, create a [free account](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn) before you begin.

<ZonePivot group="ai-foundry-portal__programming-language-csharp__programming-language-java__programming-language-javascript__programming-language-python__rest-api" options={[{"id": "programming-language-csharp", "title": "C#"}, {"id": "programming-language-java", "title": "Java"}, {"id": "programming-language-javascript", "title": "JavaScript"}, {"id": "programming-language-python", "title": "Python"}, {"id": "rest-api", "title": "REST API"}, {"id": "ai-foundry-portal", "title": "Foundry portal"}]} defaultValue="programming-language-csharp" />

<ZoneContent group="ai-foundry-portal__programming-language-csharp__programming-language-java__programming-language-javascript__programming-language-python__rest-api" value="programming-language-csharp" options={[{"id": "programming-language-csharp", "title": "C#"}, {"id": "programming-language-java", "title": "Java"}, {"id": "programming-language-javascript", "title": "JavaScript"}, {"id": "programming-language-python", "title": "Python"}, {"id": "rest-api", "title": "REST API"}, {"id": "ai-foundry-portal", "title": "Foundry portal"}]} values={["programming-language-csharp", "programming-language-java", "programming-language-javascript", "programming-language-python", "rest-api", "ai-foundry-portal"]} defaultValue="programming-language-csharp">
  [Reference documentation](https://learn.microsoft.com/dotnet/api/azure.ai.textanalytics) | [More samples](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/textanalytics/Azure.AI.TextAnalytics/samples) | [Package (NuGet)](https://www.nuget.org/packages/Azure.AI.TextAnalytics/5.2.0) | [Library source code](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/textanalytics/Azure.AI.TextAnalytics)

  Use this quickstart to create a language detection application with the client library for .NET. In the following example, you create a C# application that can identify the language a text sample was written in.

  ## Prerequisites

  * Azure subscription - [Create one for free](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn)
  * The [Visual Studio IDE](https://visualstudio.microsoft.com/vs/)

  ## Setting up

  ### Create an Azure resource

  To use the code sample below, you need to deploy an Azure resource. This resource will contain a key and endpoint you use to authenticate the API calls you send to Azure Language.

  1. Use the following link to <a href="https://portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics" target="_blank">create a language resource</a> using the Azure portal. You need to sign in using your Azure subscription.
  2. On the **Select additional features** screen that appears, select **Continue to create your resource**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-additional-features.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=a43ef31ab2c779cab7d289e7ff37916a" alt="A screenshot showing additional feature options in the Azure portal." width="1770" height="1183" data-path="images/portal-resource-additional-features.png" />
  </Frame>

  1. In the **Create language** screen, provide the following information:

     | Detail         | Description                                                                                                                                                                                                                                                                   |
     | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
     | Subscription   | The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.                                                                                                                                                  |
     | Resource group | A resource group is a container that stores the resources you create. Select **Create new** to create a new resource group.                                                                                                                                                   |
     | Region         | The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose **East US**. |
     | Name           | The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.                                                                                                                              |
     | Pricing tier   | The [pricing tier](https://azure.microsoft.com/pricing/details/cognitive-services/language-service/) for your Language resource. You can use the **Free F0** tier to try the service and upgrade later to a paid tier for production.                                         |

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-creation-details.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=75f6b5d01ec5e0617f22baa67b67f55a" alt="A screenshot showing resource creation details in the Azure portal." width="1791" height="1467" data-path="images/portal-resource-creation-details.png" />
  </Frame>

  1. Make sure the **Responsible AI Notice** checkbox is checked.

  2. Select **Review + Create** at the bottom of the page.

  3. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select **Create**.

  ### Get your key and endpoint

  Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After Azure Language resource deploys successfully, click the **Go to Resource** button under **Next Steps**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-next-steps.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=5643bd29c9450d97e99a6131d34cffa2" alt="A screenshot showing the next steps after a resource has deployed." width="2031" height="691" data-path="images/portal-resource-next-steps.png" />
  </Frame>

  1. On the screen for your resource, select **Keys and endpoint** on the left pane. You will use one of your keys and your endpoint in the steps below.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/0VPAxvMMXPvOqmAj/images/azure-portal-resource-credentials.png?fit=max&auto=format&n=0VPAxvMMXPvOqmAj&q=85&s=354d1fffe41a805e8e10d7c70f8f81dd" alt="A screenshot showing the keys and endpoint section for a resource." width="1569" height="883" data-path="images/azure-portal-resource-credentials.png" />
  </Frame>

  ### Create environment variables

  Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

  To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  * To set the `LANGUAGE_KEY` environment variable, replace `your-key` with one of the keys for your resource.
  * To set the `LANGUAGE_ENDPOINT` environment variable, replace `your-endpoint` with the endpoint for your resource.

  <Tabs>
    <Tab title="Windows">
      ```console theme={null}
      setx LANGUAGE_KEY your-key
      ```

      ```console theme={null}
      setx LANGUAGE_ENDPOINT your-endpoint
      ```

      <Note>
        If you only need to access the environment variables in the current running console, you can set the environment variable with `set` instead of `setx`.
      </Note>

      After you add the environment variables, you might need to restart any running programs that will need to read the environment variables, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
    </Tab>

    <Tab title="Linux">
      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bashrc` from your console window to make the changes effective.
    </Tab>

    <Tab title="macOS">
      ##### Bash

      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bash_profile` from your console window to make the changes effective.

      ##### Xcode

      For iOS and macOS development, you set the environment variables in Xcode. For example, follow these steps to set the environment variable in Xcode 13.4.1.

      1. Select **Product** > **Scheme** > **Edit scheme**
      2. Select **Arguments** on the **Run** (Debug Run) page
      3. Under **Environment Variables** select the plus (+) sign to add a new environment variable.
      4. Enter `LANGUAGE_KEY` for the **Name** and enter your Language resource key for the **Value**.
      5. Perform these steps for your resource endpoint. Name the new environment variable `LANGUAGE_ENDPOINT`.

      For more configuration options, see the [Xcode documentation](https://help.apple.com/xcode/#/dev745c5c974).
    </Tab>
  </Tabs>

  ### Create a new .NET Core application

  Using the Visual Studio IDE, create a new .NET Core console app. This creates a "Hello World" project with a single C# source file: *program.cs*.

  Install the client library by right-clicking the solution in the **Solution Explorer** and selecting **Manage NuGet Packages**. In the package manager that opens select **Browse** and search for `Azure.AI.TextAnalytics`. Select version `5.2.0`, and then **Install**. You can also use the [Package Manager Console](/nuget/consume-packages/install-use-packages-powershell#find-and-install-a-package).

  ## Code example

  Copy the following code into your *program.cs* file. Then run the code.

  ```csharp theme={null}
  using Azure;
  using System;
  using Azure.AI.TextAnalytics;

  namespace LanguageDetectionExample
  {
      class Program
      {
          // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT".
          static void LanguageDetectionExample(TextAnalyticsClient client)
          {
              DetectedLanguage detectedLanguage = client.DetectLanguage("Ce document est rédigé en Français.");
              Console.WriteLine("Language:");
              Console.WriteLine($"\t{detectedLanguage.Name},\tISO-6391: {detectedLanguage.Iso6391Name}\n");
          }

          static void Main(string[] args)
          {
              string languageKey = Environment.GetEnvironmentVariable("LANGUAGE_KEY");
              string languageEndpoint = Environment.GetEnvironmentVariable("LANGUAGE_ENDPOINT");

              if (string.IsNullOrWhiteSpace(languageKey) || string.IsNullOrWhiteSpace(languageEndpoint))
              {
                  Console.WriteLine("Set the LANGUAGE_KEY and LANGUAGE_ENDPOINT environment variables before running this sample.");
                  return;
              }

              var endpoint = new Uri(languageEndpoint);
              var credentials = new AzureKeyCredential(languageKey);
              var client = new TextAnalyticsClient(endpoint, credentials);

              LanguageDetectionExample(client);

              Console.Write("Press any key to exit.");
              Console.ReadKey();
          }

      }
  }

  ```

  ### Output

  ```console theme={null}
  Language:
      French, ISO-6391: fr
  ```
</ZoneContent>

<ZoneContent group="ai-foundry-portal__programming-language-csharp__programming-language-java__programming-language-javascript__programming-language-python__rest-api" value="programming-language-java" options={[{"id": "programming-language-csharp", "title": "C#"}, {"id": "programming-language-java", "title": "Java"}, {"id": "programming-language-javascript", "title": "JavaScript"}, {"id": "programming-language-python", "title": "Python"}, {"id": "rest-api", "title": "REST API"}, {"id": "ai-foundry-portal", "title": "Foundry portal"}]} values={["programming-language-csharp", "programming-language-java", "programming-language-javascript", "programming-language-python", "rest-api", "ai-foundry-portal"]} defaultValue="programming-language-csharp">
  [Reference documentation](https://learn.microsoft.com/java/api/overview/azure/ai-textanalytics-readme) | [More samples](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/textanalytics/azure-ai-textanalytics/src/samples) | [Package (Maven)](https://mvnrepository.com/artifact/com.azure/azure-ai-textanalytics/5.2.0) | [Library source code](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/textanalytics/azure-ai-textanalytics)

  Use this quickstart to create a language detection application with the client library for Java. In the following example, you create a Java application that can identify the language a text sample was written in.

  ## Prerequisites

  * Azure subscription - [Create one for free](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn)
  * [Java Development Kit (JDK)](https://www.oracle.com/technetwork/java/javase/downloads/index.html) with version 8 or above

  ## Setting up

  ### Create an Azure resource

  To use the code sample below, you need to deploy an Azure resource. This resource will contain a key and endpoint you use to authenticate the API calls you send to Azure Language.

  1. Use the following link to <a href="https://portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics" target="_blank">create a language resource</a> using the Azure portal. You need to sign in using your Azure subscription.
  2. On the **Select additional features** screen that appears, select **Continue to create your resource**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-additional-features.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=a43ef31ab2c779cab7d289e7ff37916a" alt="A screenshot showing additional feature options in the Azure portal." width="1770" height="1183" data-path="images/portal-resource-additional-features.png" />
  </Frame>

  1. In the **Create language** screen, provide the following information:

     | Detail         | Description                                                                                                                                                                                                                                                                   |
     | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
     | Subscription   | The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.                                                                                                                                                  |
     | Resource group | A resource group is a container that stores the resources you create. Select **Create new** to create a new resource group.                                                                                                                                                   |
     | Region         | The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose **East US**. |
     | Name           | The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.                                                                                                                              |
     | Pricing tier   | The [pricing tier](https://azure.microsoft.com/pricing/details/cognitive-services/language-service/) for your Language resource. You can use the **Free F0** tier to try the service and upgrade later to a paid tier for production.                                         |

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-creation-details.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=75f6b5d01ec5e0617f22baa67b67f55a" alt="A screenshot showing resource creation details in the Azure portal." width="1791" height="1467" data-path="images/portal-resource-creation-details.png" />
  </Frame>

  1. Make sure the **Responsible AI Notice** checkbox is checked.

  2. Select **Review + Create** at the bottom of the page.

  3. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select **Create**.

  ### Get your key and endpoint

  Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After Azure Language resource deploys successfully, click the **Go to Resource** button under **Next Steps**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-next-steps.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=5643bd29c9450d97e99a6131d34cffa2" alt="A screenshot showing the next steps after a resource has deployed." width="2031" height="691" data-path="images/portal-resource-next-steps.png" />
  </Frame>

  1. On the screen for your resource, select **Keys and endpoint** on the left pane. You will use one of your keys and your endpoint in the steps below.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/0VPAxvMMXPvOqmAj/images/azure-portal-resource-credentials.png?fit=max&auto=format&n=0VPAxvMMXPvOqmAj&q=85&s=354d1fffe41a805e8e10d7c70f8f81dd" alt="A screenshot showing the keys and endpoint section for a resource." width="1569" height="883" data-path="images/azure-portal-resource-credentials.png" />
  </Frame>

  ### Create environment variables

  Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

  To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  * To set the `LANGUAGE_KEY` environment variable, replace `your-key` with one of the keys for your resource.
  * To set the `LANGUAGE_ENDPOINT` environment variable, replace `your-endpoint` with the endpoint for your resource.

  <Tabs>
    <Tab title="Windows">
      ```console theme={null}
      setx LANGUAGE_KEY your-key
      ```

      ```console theme={null}
      setx LANGUAGE_ENDPOINT your-endpoint
      ```

      <Note>
        If you only need to access the environment variables in the current running console, you can set the environment variable with `set` instead of `setx`.
      </Note>

      After you add the environment variables, you might need to restart any running programs that will need to read the environment variables, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
    </Tab>

    <Tab title="Linux">
      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bashrc` from your console window to make the changes effective.
    </Tab>

    <Tab title="macOS">
      ##### Bash

      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bash_profile` from your console window to make the changes effective.

      ##### Xcode

      For iOS and macOS development, you set the environment variables in Xcode. For example, follow these steps to set the environment variable in Xcode 13.4.1.

      1. Select **Product** > **Scheme** > **Edit scheme**
      2. Select **Arguments** on the **Run** (Debug Run) page
      3. Under **Environment Variables** select the plus (+) sign to add a new environment variable.
      4. Enter `LANGUAGE_KEY` for the **Name** and enter your Language resource key for the **Value**.
      5. Perform these steps for your resource endpoint. Name the new environment variable `LANGUAGE_ENDPOINT`.

      For more configuration options, see the [Xcode documentation](https://help.apple.com/xcode/#/dev745c5c974).
    </Tab>
  </Tabs>

  ### Add the client library

  Create a Maven project in your preferred IDE or development environment. Then add the following dependency to your project's *pom.xml* file. You can find the implementation syntax [for other build tools](https://mvnrepository.com/artifact/com.azure/azure-ai-textanalytics/5.2.0) online.

  ```xml theme={null}
  <dependencies>
       <dependency>
          <groupId>com.azure</groupId>
          <artifactId>azure-ai-textanalytics</artifactId>
          <version>5.2.0</version>
      </dependency>
  </dependencies>
  ```

  ## Code example

  Create a Java file named `Example.java`. Open the file and copy the below code. Then run the code.

  ```java theme={null}
  import com.azure.core.credential.AzureKeyCredential;
  import com.azure.ai.textanalytics.models.*;
  import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
  import com.azure.ai.textanalytics.TextAnalyticsClient;

  public class Example {

      // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
      private static String languageKey = System.getenv("LANGUAGE_KEY");
      private static String languageEndpoint = System.getenv("LANGUAGE_ENDPOINT");

      public static void main(String[] args) {
          if (languageKey == null || languageKey.isBlank() || languageEndpoint == null || languageEndpoint.isBlank()) {
              throw new IllegalArgumentException("Missing LANGUAGE_KEY or LANGUAGE_ENDPOINT environment variables");
          }
          TextAnalyticsClient client = authenticateClient(languageKey, languageEndpoint);
          detectLanguageExample(client);
      }
      // Method to authenticate the client object with your key and endpoint
      static TextAnalyticsClient authenticateClient(String key, String endpoint) {
          return new TextAnalyticsClientBuilder()
                  .credential(new AzureKeyCredential(key))
                  .endpoint(endpoint)
                  .buildClient();
      }
      // Example method for detecting the language of text
      static void detectLanguageExample(TextAnalyticsClient client)
      {
          // The text to be analyzed.
          String text = "Ce document est rédigé en Français.";

          DetectedLanguage detectedLanguage = client.detectLanguage(text);
          System.out.printf("Detected primary language: %s, ISO 6391 name: %s, score: %.2f.%n",
                  detectedLanguage.getName(),
                  detectedLanguage.getIso6391Name(),
                  detectedLanguage.getConfidenceScore());
      }
  }

  ```

  ### Output

  ```console theme={null}
  Detected primary language: French, ISO 6391 name: fr, score: 1.00.
  ```
</ZoneContent>

<ZoneContent group="ai-foundry-portal__programming-language-csharp__programming-language-java__programming-language-javascript__programming-language-python__rest-api" value="programming-language-javascript" options={[{"id": "programming-language-csharp", "title": "C#"}, {"id": "programming-language-java", "title": "Java"}, {"id": "programming-language-javascript", "title": "JavaScript"}, {"id": "programming-language-python", "title": "Python"}, {"id": "rest-api", "title": "REST API"}, {"id": "ai-foundry-portal", "title": "Foundry portal"}]} values={["programming-language-csharp", "programming-language-java", "programming-language-javascript", "programming-language-python", "rest-api", "ai-foundry-portal"]} defaultValue="programming-language-csharp">
  [Reference documentation](https://learn.microsoft.com/javascript/api/overview/azure/ai-language-text-readme) | [More samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cognitivelanguage/ai-language-text/samples/v1) | [Package (npm)](https://www.npmjs.com/package/@azure/ai-language-text) | [Library source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cognitivelanguage/ai-language-text)

  Use this quickstart to create a language detection application with the client library for Node.js. In the following example, you create a JavaScript application that can identify the language a text sample was written in.

  ## Prerequisites

  * Azure subscription - [Create one for free](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn)
  * [Node.js](https://nodejs.org/) v14 LTS or later

  ## Setting up

  ### Create an Azure resource

  To use the code sample below, you need to deploy an Azure resource. This resource will contain a key and endpoint you use to authenticate the API calls you send to Azure Language.

  1. Use the following link to <a href="https://portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics" target="_blank">create a language resource</a> using the Azure portal. You need to sign in using your Azure subscription.
  2. On the **Select additional features** screen that appears, select **Continue to create your resource**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-additional-features.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=a43ef31ab2c779cab7d289e7ff37916a" alt="A screenshot showing additional feature options in the Azure portal." width="1770" height="1183" data-path="images/portal-resource-additional-features.png" />
  </Frame>

  1. In the **Create language** screen, provide the following information:

     | Detail         | Description                                                                                                                                                                                                                                                                   |
     | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
     | Subscription   | The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.                                                                                                                                                  |
     | Resource group | A resource group is a container that stores the resources you create. Select **Create new** to create a new resource group.                                                                                                                                                   |
     | Region         | The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose **East US**. |
     | Name           | The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.                                                                                                                              |
     | Pricing tier   | The [pricing tier](https://azure.microsoft.com/pricing/details/cognitive-services/language-service/) for your Language resource. You can use the **Free F0** tier to try the service and upgrade later to a paid tier for production.                                         |

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-creation-details.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=75f6b5d01ec5e0617f22baa67b67f55a" alt="A screenshot showing resource creation details in the Azure portal." width="1791" height="1467" data-path="images/portal-resource-creation-details.png" />
  </Frame>

  1. Make sure the **Responsible AI Notice** checkbox is checked.

  2. Select **Review + Create** at the bottom of the page.

  3. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select **Create**.

  ### Get your key and endpoint

  Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After Azure Language resource deploys successfully, click the **Go to Resource** button under **Next Steps**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-next-steps.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=5643bd29c9450d97e99a6131d34cffa2" alt="A screenshot showing the next steps after a resource has deployed." width="2031" height="691" data-path="images/portal-resource-next-steps.png" />
  </Frame>

  1. On the screen for your resource, select **Keys and endpoint** on the left pane. You will use one of your keys and your endpoint in the steps below.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/0VPAxvMMXPvOqmAj/images/azure-portal-resource-credentials.png?fit=max&auto=format&n=0VPAxvMMXPvOqmAj&q=85&s=354d1fffe41a805e8e10d7c70f8f81dd" alt="A screenshot showing the keys and endpoint section for a resource." width="1569" height="883" data-path="images/azure-portal-resource-credentials.png" />
  </Frame>

  ### Create environment variables

  Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

  To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  * To set the `LANGUAGE_KEY` environment variable, replace `your-key` with one of the keys for your resource.
  * To set the `LANGUAGE_ENDPOINT` environment variable, replace `your-endpoint` with the endpoint for your resource.

  <Tabs>
    <Tab title="Windows">
      ```console theme={null}
      setx LANGUAGE_KEY your-key
      ```

      ```console theme={null}
      setx LANGUAGE_ENDPOINT your-endpoint
      ```

      <Note>
        If you only need to access the environment variables in the current running console, you can set the environment variable with `set` instead of `setx`.
      </Note>

      After you add the environment variables, you might need to restart any running programs that will need to read the environment variables, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
    </Tab>

    <Tab title="Linux">
      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bashrc` from your console window to make the changes effective.
    </Tab>

    <Tab title="macOS">
      ##### Bash

      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bash_profile` from your console window to make the changes effective.

      ##### Xcode

      For iOS and macOS development, you set the environment variables in Xcode. For example, follow these steps to set the environment variable in Xcode 13.4.1.

      1. Select **Product** > **Scheme** > **Edit scheme**
      2. Select **Arguments** on the **Run** (Debug Run) page
      3. Under **Environment Variables** select the plus (+) sign to add a new environment variable.
      4. Enter `LANGUAGE_KEY` for the **Name** and enter your Language resource key for the **Value**.
      5. Perform these steps for your resource endpoint. Name the new environment variable `LANGUAGE_ENDPOINT`.

      For more configuration options, see the [Xcode documentation](https://help.apple.com/xcode/#/dev745c5c974).
    </Tab>
  </Tabs>

  ### Create a new Node.js application

  In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

  ```console theme={null}
  mkdir myapp 

  cd myapp
  ```

  Run the `npm init` command to create a node application with a `package.json` file.

  ```console theme={null}
  npm init
  ```

  ### Install the client library

  Install the npm package:

  ```console theme={null}
  npm install @azure/ai-language-text
  ```

  ## Code example

  Open the file and copy the below code. Then run the code.

  ```javascript theme={null}
  "use strict";

  const { AzureKeyCredential, TextAnalysisClient } = require("@azure/ai-language-text");

  // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
  const key = process.env.LANGUAGE_KEY;
  const endpoint = process.env.LANGUAGE_ENDPOINT;

  if (!key || !endpoint) {
    throw new Error(
      "Missing LANGUAGE_KEY or LANGUAGE_ENDPOINT environment variables."
    );
  }

  //Example sentences in different languages to be analyzed
  const documents = [
      "This document is written in English.",
      "这是一个用中文写的文件",
  ];

  //Example of how to use the client library to detect language
  async function main() {
      console.log("== Language detection sample ==");
    
      const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(key));
    
      const result = await client.analyze("LanguageDetection", documents);
    
      for (const doc of result) {
        if (!doc.error) {
          console.log(
            `ID ${doc.id} - Primary language: ${doc.primaryLanguage.name} (iso6391 name: ${doc.primaryLanguage.iso6391Name})`
          );
        }
      }
  }

  main().catch((err) => {
      console.error("The sample encountered an error:", err);
  });
  ```

  ### Output

  ```console theme={null}
  == Language detection sample ==
  ID 0 - Primary language: English (iso6391 name: en)
  ID 1 - Primary language: Chinese_Simplified (iso6391 name: zh_chs)
  ```
</ZoneContent>

<ZoneContent group="ai-foundry-portal__programming-language-csharp__programming-language-java__programming-language-javascript__programming-language-python__rest-api" value="programming-language-python" options={[{"id": "programming-language-csharp", "title": "C#"}, {"id": "programming-language-java", "title": "Java"}, {"id": "programming-language-javascript", "title": "JavaScript"}, {"id": "programming-language-python", "title": "Python"}, {"id": "rest-api", "title": "REST API"}, {"id": "ai-foundry-portal", "title": "Foundry portal"}]} values={["programming-language-csharp", "programming-language-java", "programming-language-javascript", "programming-language-python", "rest-api", "ai-foundry-portal"]} defaultValue="programming-language-csharp">
  [Reference documentation](https://learn.microsoft.com/python/api/azure-ai-textanalytics/azure.ai.textanalytics) | [More samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/textanalytics/azure-ai-textanalytics/samples) | [Package (PyPi)](https://pypi.org/project/azure-ai-textanalytics/5.2.0/) | [Library source code](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/textanalytics/azure-ai-textanalytics)

  Use this quickstart to create a language detection application with the client library for Python. In the following example, you create a Python application that can identify the language a text sample was written in.

  <Tip>
    You can use [**Microsoft Foundry**](https://ai.azure.com/) to try Azure Language features without needing to write code.
  </Tip>

  ## Prerequisites

  * Azure subscription - [Create one for free](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn)
  * [Python 3.8 or later](https://www.python.org/)

  ## Setting up

  ### Create an Azure resource

  To use the code sample below, you need to deploy an Azure resource. This resource will contain a key and endpoint you use to authenticate the API calls you send to Azure Language.

  1. Use the following link to <a href="https://portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics" target="_blank">create a language resource</a> using the Azure portal. You need to sign in using your Azure subscription.
  2. On the **Select additional features** screen that appears, select **Continue to create your resource**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-additional-features.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=a43ef31ab2c779cab7d289e7ff37916a" alt="A screenshot showing additional feature options in the Azure portal." width="1770" height="1183" data-path="images/portal-resource-additional-features.png" />
  </Frame>

  1. In the **Create language** screen, provide the following information:

     | Detail         | Description                                                                                                                                                                                                                                                                   |
     | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
     | Subscription   | The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.                                                                                                                                                  |
     | Resource group | A resource group is a container that stores the resources you create. Select **Create new** to create a new resource group.                                                                                                                                                   |
     | Region         | The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose **East US**. |
     | Name           | The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.                                                                                                                              |
     | Pricing tier   | The [pricing tier](https://azure.microsoft.com/pricing/details/cognitive-services/language-service/) for your Language resource. You can use the **Free F0** tier to try the service and upgrade later to a paid tier for production.                                         |

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-creation-details.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=75f6b5d01ec5e0617f22baa67b67f55a" alt="A screenshot showing resource creation details in the Azure portal." width="1791" height="1467" data-path="images/portal-resource-creation-details.png" />
  </Frame>

  1. Make sure the **Responsible AI Notice** checkbox is checked.

  2. Select **Review + Create** at the bottom of the page.

  3. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select **Create**.

  ### Get your key and endpoint

  Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After Azure Language resource deploys successfully, click the **Go to Resource** button under **Next Steps**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-next-steps.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=5643bd29c9450d97e99a6131d34cffa2" alt="A screenshot showing the next steps after a resource has deployed." width="2031" height="691" data-path="images/portal-resource-next-steps.png" />
  </Frame>

  1. On the screen for your resource, select **Keys and endpoint** on the left pane. You will use one of your keys and your endpoint in the steps below.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/0VPAxvMMXPvOqmAj/images/azure-portal-resource-credentials.png?fit=max&auto=format&n=0VPAxvMMXPvOqmAj&q=85&s=354d1fffe41a805e8e10d7c70f8f81dd" alt="A screenshot showing the keys and endpoint section for a resource." width="1569" height="883" data-path="images/azure-portal-resource-credentials.png" />
  </Frame>

  ### Create environment variables

  Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

  To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  * To set the `LANGUAGE_KEY` environment variable, replace `your-key` with one of the keys for your resource.
  * To set the `LANGUAGE_ENDPOINT` environment variable, replace `your-endpoint` with the endpoint for your resource.

  <Tabs>
    <Tab title="Windows">
      ```console theme={null}
      setx LANGUAGE_KEY your-key
      ```

      ```console theme={null}
      setx LANGUAGE_ENDPOINT your-endpoint
      ```

      <Note>
        If you only need to access the environment variables in the current running console, you can set the environment variable with `set` instead of `setx`.
      </Note>

      After you add the environment variables, you might need to restart any running programs that will need to read the environment variables, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
    </Tab>

    <Tab title="Linux">
      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bashrc` from your console window to make the changes effective.
    </Tab>

    <Tab title="macOS">
      ##### Bash

      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bash_profile` from your console window to make the changes effective.

      ##### Xcode

      For iOS and macOS development, you set the environment variables in Xcode. For example, follow these steps to set the environment variable in Xcode 13.4.1.

      1. Select **Product** > **Scheme** > **Edit scheme**
      2. Select **Arguments** on the **Run** (Debug Run) page
      3. Under **Environment Variables** select the plus (+) sign to add a new environment variable.
      4. Enter `LANGUAGE_KEY` for the **Name** and enter your Language resource key for the **Value**.
      5. Perform these steps for your resource endpoint. Name the new environment variable `LANGUAGE_ENDPOINT`.

      For more configuration options, see the [Xcode documentation](https://help.apple.com/xcode/#/dev745c5c974).
    </Tab>
  </Tabs>

  ### Install the client library

  After installing Python, you can install the client library with:

  ```console theme={null}
  pip install azure-ai-textanalytics==5.2.0
  ```

  ## Code example

  Create a new Python file and copy the below code. Then run the code.

  ```python theme={null}
  # This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
  import os

  from azure.ai.textanalytics import TextAnalyticsClient
  from azure.core.credentials import AzureKeyCredential

  language_key = os.environ.get("LANGUAGE_KEY")
  language_endpoint = os.environ.get("LANGUAGE_ENDPOINT")

  if not language_key or not language_endpoint:
      raise ValueError("Missing LANGUAGE_KEY or LANGUAGE_ENDPOINT environment variables")

  # Authenticate the client using your key and endpoint
  def authenticate_client():
      ta_credential = AzureKeyCredential(language_key)
      text_analytics_client = TextAnalyticsClient(
              endpoint=language_endpoint,
              credential=ta_credential)
      return text_analytics_client

  client = authenticate_client()

  # Example method for detecting the language of text
  def language_detection_example(client):
      try:
          documents = ["Ce document est rédigé en Français."]
          response = client.detect_language(documents = documents, country_hint = 'us')[0]
          print("Language: ", response.primary_language.name)

      except Exception as err:
          print("Encountered exception. {}".format(err))
  language_detection_example(client)
  ```

  ### Output

  ```console theme={null}
  Language:  French
  ```
</ZoneContent>

<ZoneContent group="ai-foundry-portal__programming-language-csharp__programming-language-java__programming-language-javascript__programming-language-python__rest-api" value="rest-api" options={[{"id": "programming-language-csharp", "title": "C#"}, {"id": "programming-language-java", "title": "Java"}, {"id": "programming-language-javascript", "title": "JavaScript"}, {"id": "programming-language-python", "title": "Python"}, {"id": "rest-api", "title": "REST API"}, {"id": "ai-foundry-portal", "title": "Foundry portal"}]} values={["programming-language-csharp", "programming-language-java", "programming-language-javascript", "programming-language-python", "rest-api", "ai-foundry-portal"]} defaultValue="programming-language-csharp">
  [Reference documentation](https://go.microsoft.com/fwlink/?linkid=2239169)

  Use this quickstart to send language detection requests using the REST API. In the following example, you use cURL to identify the language that a text sample was written in.

  ## Prerequisites

  * Azure subscription - [Create one for free](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn)

  ## Setting up

  ### Create an Azure resource

  To use the code sample below, you need to deploy an Azure resource. This resource will contain a key and endpoint you use to authenticate the API calls you send to Azure Language.

  1. Use the following link to <a href="https://portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics" target="_blank">create a language resource</a> using the Azure portal. You need to sign in using your Azure subscription.
  2. On the **Select additional features** screen that appears, select **Continue to create your resource**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-additional-features.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=a43ef31ab2c779cab7d289e7ff37916a" alt="A screenshot showing additional feature options in the Azure portal." width="1770" height="1183" data-path="images/portal-resource-additional-features.png" />
  </Frame>

  1. In the **Create language** screen, provide the following information:

     | Detail         | Description                                                                                                                                                                                                                                                                   |
     | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
     | Subscription   | The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.                                                                                                                                                  |
     | Resource group | A resource group is a container that stores the resources you create. Select **Create new** to create a new resource group.                                                                                                                                                   |
     | Region         | The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose **East US**. |
     | Name           | The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.                                                                                                                              |
     | Pricing tier   | The [pricing tier](https://azure.microsoft.com/pricing/details/cognitive-services/language-service/) for your Language resource. You can use the **Free F0** tier to try the service and upgrade later to a paid tier for production.                                         |

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-creation-details.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=75f6b5d01ec5e0617f22baa67b67f55a" alt="A screenshot showing resource creation details in the Azure portal." width="1791" height="1467" data-path="images/portal-resource-creation-details.png" />
  </Frame>

  1. Make sure the **Responsible AI Notice** checkbox is checked.

  2. Select **Review + Create** at the bottom of the page.

  3. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select **Create**.

  ### Get your key and endpoint

  Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After Azure Language resource deploys successfully, click the **Go to Resource** button under **Next Steps**.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/portal-resource-next-steps.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=5643bd29c9450d97e99a6131d34cffa2" alt="A screenshot showing the next steps after a resource has deployed." width="2031" height="691" data-path="images/portal-resource-next-steps.png" />
  </Frame>

  1. On the screen for your resource, select **Keys and endpoint** on the left pane. You will use one of your keys and your endpoint in the steps below.

  <Frame>
    <img src="https://mintcdn.com/hobbyist-e43fa225/0VPAxvMMXPvOqmAj/images/azure-portal-resource-credentials.png?fit=max&auto=format&n=0VPAxvMMXPvOqmAj&q=85&s=354d1fffe41a805e8e10d7c70f8f81dd" alt="A screenshot showing the keys and endpoint section for a resource." width="1569" height="883" data-path="images/azure-portal-resource-credentials.png" />
  </Frame>

  ### Create environment variables

  Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

  To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  * To set the `LANGUAGE_KEY` environment variable, replace `your-key` with one of the keys for your resource.
  * To set the `LANGUAGE_ENDPOINT` environment variable, replace `your-endpoint` with the endpoint for your resource.

  <Tabs>
    <Tab title="Windows">
      ```console theme={null}
      setx LANGUAGE_KEY your-key
      ```

      ```console theme={null}
      setx LANGUAGE_ENDPOINT your-endpoint
      ```

      <Note>
        If you only need to access the environment variables in the current running console, you can set the environment variable with `set` instead of `setx`.
      </Note>

      After you add the environment variables, you might need to restart any running programs that will need to read the environment variables, including the console window. For example, if you're using Visual Studio as your editor, restart Visual Studio before running the example.
    </Tab>

    <Tab title="Linux">
      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bashrc` from your console window to make the changes effective.
    </Tab>

    <Tab title="macOS">
      ##### Bash

      ```bash theme={null}
      export LANGUAGE_KEY=your-key
      ```

      ```bash theme={null}
      export LANGUAGE_ENDPOINT=your-endpoint
      ```

      After you add the environment variables, run `source ~/.bash_profile` from your console window to make the changes effective.

      ##### Xcode

      For iOS and macOS development, you set the environment variables in Xcode. For example, follow these steps to set the environment variable in Xcode 13.4.1.

      1. Select **Product** > **Scheme** > **Edit scheme**
      2. Select **Arguments** on the **Run** (Debug Run) page
      3. Under **Environment Variables** select the plus (+) sign to add a new environment variable.
      4. Enter `LANGUAGE_KEY` for the **Name** and enter your Language resource key for the **Value**.
      5. Perform these steps for your resource endpoint. Name the new environment variable `LANGUAGE_ENDPOINT`.

      For more configuration options, see the [Xcode documentation](https://help.apple.com/xcode/#/dev745c5c974).
    </Tab>
  </Tabs>

  ## Create a JSON file with the example request body

  In a code editor, create a new file named `test_languagedetection_payload.json` and copy the following JSON example. This example request will be sent to the API in the next step.

  ```json theme={null}
  {
      "kind": "LanguageDetection",
      "parameters": {
          "modelVersion": "latest"
      },
      "analysisInput":{
          "documents":[
              {
                  "id":"1",
                  "text": "This is a document written in English."
              }
          ]
      }
  }
  ```

  Save `test_languagedetection_payload.json` somewhere on your computer. For example, your desktop.

  ## Send a language detection request

  Use the following commands to send the API request using the program you're using. Copy the command into your terminal, and run it.

  | Parameter                             | Description                                         |
  | ------------------------------------- | --------------------------------------------------- |
  | `-X POST <endpoint>`                  | Specifies your endpoint for accessing the API.      |
  | `-H Content-Type: application/json`   | The content type for sending JSON data.             |
  | `-H "Ocp-Apim-Subscription-Key:<key>` | Specifies the key for accessing the API.            |
  | `-d <documents>`                      | The JSON containing the documents you want to send. |

  <Tabs>
    <Tab title="Windows">
      Replace `C:\Users\<myaccount>\Desktop\test_languagedetection_payload.json` with the location of the example JSON request file you created in the previous step.

      ### Command prompt

      ```terminal theme={null}
      curl -X POST "%LANGUAGE_ENDPOINT%/language/:analyze-text?api-version=2023-11-15-preview" ^
      -H "Content-Type: application/json" ^
      -H "Ocp-Apim-Subscription-Key: %LANGUAGE_KEY%" ^
      -d "@C:\Users\<myaccount>\Desktop\test_languagedetection_payload.json"
      ```

      ### PowerShell

      ```terminal theme={null}
      curl.exe -X POST $env:LANGUAGE_ENDPOINT/language/:analyze-text?api-version=2023-11-15-preview `
      -H "Content-Type: application/json" `
      -H "Ocp-Apim-Subscription-Key: $env:LANGUAGE_KEY" `
      -d "@C:\Users\<myaccount>\Desktop\test_languagedetection_payload.json"
      ```
    </Tab>

    <Tab title="Linux">
      Use the following commands to send the API request using the program you're using. Replace `/home/mydir/test_languagedetection_payload.json` with the location of the example JSON request file you created in the previous step.

      ```terminal theme={null}
      curl -X POST $LANGUAGE_ENDPOINT/language/:analyze-text?api-version=2023-11-15-preview \
      -H "Content-Type: application/json" \
      -H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY" \
      -d "@/home/mydir/test_languagedetection_payload.json"
      ```
    </Tab>

    <Tab title="macOS">
      Use the following commands to send the API request using the program you're using. Replace `/home/mydir/test_languagedetection_payload.json` with the location of the example JSON request file you created in the previous step.

      ```terminal theme={null}
      curl -X POST $LANGUAGE_ENDPOINT/language/:analyze-text?api-version=2023-11-15-preview \
      -H "Content-Type: application/json" \
      -H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY" \
      -d "@/home/mydir/test_languagedetection_payload.json"
      ```
    </Tab>
  </Tabs>

  ## JSON response

  ```json theme={null}
  {
      "kind": "LanguageDetectionResults",
      "results": {
          "documents": [
              {
                  "id": "1",
                  "detectedLanguage": {
                      "name": "English",
                      "iso6391Name": "en",
                      "confidenceScore": 1.0,
                      "script": "Latin",
                      "scriptCode": "Latn"
                  },
                  "warnings": []
              }
          ],
          "errors": [],
          "modelVersion": "2023-12-01"
      }
  }
  ```

  Use the following commands to delete the environment variables you created for this quickstart.

  <CodeGroup>
    ```console Windows theme={null}
        reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
    ```

    ```console Windows theme={null}
        reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f
    ```

    ```bash Linux theme={null}
        unset LANGUAGE_KEY
    ```

    ```bash Linux theme={null}
        unset LANGUAGE_ENDPOINT
    ```

    ```bash macOS theme={null}
        unset LANGUAGE_KEY
    ```

    ```bash macOS theme={null}
        unset LANGUAGE_ENDPOINT
    ```
  </CodeGroup>
</ZoneContent>

<ZoneContent group="ai-foundry-portal__programming-language-csharp__programming-language-java__programming-language-javascript__programming-language-python__rest-api" value="ai-foundry-portal" options={[{"id": "programming-language-csharp", "title": "C#"}, {"id": "programming-language-java", "title": "Java"}, {"id": "programming-language-javascript", "title": "JavaScript"}, {"id": "programming-language-python", "title": "Python"}, {"id": "rest-api", "title": "REST API"}, {"id": "ai-foundry-portal", "title": "Foundry portal"}]} values={["programming-language-csharp", "programming-language-java", "programming-language-javascript", "programming-language-python", "rest-api", "ai-foundry-portal"]} defaultValue="programming-language-csharp">
  ## Prerequisites

  * **Azure subscription**. If you don't have one, you can [create one for free](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn).
  * **Requisite permissions**. Make sure the person establishing the account and project has the Foundry Account Owner role at the subscription level assigned. Alternatively, the **Contributor** or **Cognitive Services Contributor** role at the subscription scope also meets this requirement. For more information, see [Role based access control (RBAC)](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/role-based-access-control#cognitive-services-contributor).

  <Info />

  > The Foundry RBAC roles were recently renamed. **Foundry User**, **Foundry Owner**, **Foundry Account Owner**, and **Foundry Project Manager** were previously named Azure AI User, Azure AI Owner, Azure AI Account Owner, and Azure AI Project Manager. You might still see the previous names in some places while the rename rolls out. The role IDs and core permissions are unchanged by the rename.

  * **Foundry resource**. Create a [Foundry resource](../../../../multi-service-resource) or see [Configure a Foundry resource](../../../concepts/configure-azure-resources). Alternatively, you can use a [Language resource](https://portal.azure.com/?Microsoft_Azure_PIMCommon=true#create/Microsoft.CognitiveServicesTextAnalytics).
  * **A Foundry project**. For more information, see [Create a Foundry project](https://learn.microsoft.com/en-us/azure/ai-foundry/how-to/create-projects).

  <Tabs>
    <Tab title="Foundry (classic)">
      <Note>
        This content refers to the [Foundry (classic)](https://ai.azure.com/) portal, which supports hub-based projects and other resource types. To confirm that you're using Foundry (classic), make sure the version toggle in the portal banner is in the **off** position. <img src="https://mintcdn.com/hobbyist-e43fa225/i8cG-y5gTtUVot10/images/classic-foundry.png?fit=max&auto=format&n=i8cG-y5gTtUVot10&q=85&s=3cbdc91c816894804a08542085e32659" width="184" height="36" data-path="images/classic-foundry.png" />
      </Note>

      You can use [Foundry (classic)](https://ai.azure.com/) to:

      * Detect the language of input text
      * Review confidence scores and ISO language codes
      * Configure country/region hints for improved accuracy

      ## Navigate to the Foundry (classic) playground

      1. In the left pane, select **Playgrounds**.
      2. Select the **Try Azure Language Playground** button.

      <Frame>
        <img src="https://mintcdn.com/hobbyist-e43fa225/Ys-Pfvj6qDB8iZQ8/images/foundry-playground-navigation.png?fit=max&auto=format&n=Ys-Pfvj6qDB8iZQ8&q=85&s=613f70f2938c5dabfd493c9978ec264d" alt="Screenshot showing the Playgrounds navigation and the Try Azure Language Playground button in Foundry (classic)." width="1304" height="1171" data-path="images/foundry-playground-navigation.png" />
      </Frame>

      ## Detect language in the Foundry playground

      The **Language playground** consists of four sections:

      | Section         | Purpose                                                                                    |
      | --------------- | ------------------------------------------------------------------------------------------ |
      | **Top banner**  | Select the **Detect language** tile.                                                       |
      | **Left pane**   | Set **Configuration** options such as API version, model version, and country/region hint. |
      | **Center pane** | Enter text for processing and review results.                                              |
      | **Right pane**  | View **Details** for detected language and script.                                         |

      1. Select the **Detect language** tile from the top banner.

      2. Enter or paste text in the center pane.

      3. In the **Configuration** pane, set the following options:

         | Option                     | Description                                         |
         | -------------------------- | --------------------------------------------------- |
         | Select API version         | Select which version of the API to use.             |
         | Select model version       | Select which version of the model to use.           |
         | Select country/region hint | Select the origin country/region of the input text. |

      4. Select the **Run** button to detect the language.

      After the operation completes, the **Details** section displays the following fields for the detected language and script:

      | Field                 | Description                                                                 |
      | --------------------- | --------------------------------------------------------------------------- |
      | ISO 639-1 Code        | The ISO 639-1 two-letter code for the detected language.                    |
      | Confidence Score      | The model's level of certainty that the language identification is correct. |
      | Script Name           | The name of the detected script in the text.                                |
      | ISO 15924 Script Code | The ISO 15924 code for the detected script (writing system).                |

      <Frame>
        <img src="https://mintcdn.com/hobbyist-e43fa225/Ys-Pfvj6qDB8iZQ8/images/language-detection.png?fit=max&auto=format&n=Ys-Pfvj6qDB8iZQ8&q=85&s=cdd7e347a50acc61fb031a9840d9fc90" alt="A screenshot showing language detection results with confidence scores and ISO codes displayed in the Details pane of the Foundry portal." width="1436" height="718" data-path="images/language-detection.png" />
      </Frame>

      Verify that the detected language matches the language of your input text. If the result shows `unknown`, provide a longer text sample or set a **Country/region hint** for better accuracy.
    </Tab>

    <Tab title="New Foundry">
      <Note>
        This content refers to the [new Foundry](https://ai.azure.com/) portal, which supports only Foundry projects and provides streamlined access to models, agents, and tools. For more information, see [What is Microsoft Foundry?](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-foundry). To confirm that you're using new Foundry, make sure the version toggle in the portal banner is in the **on** position. <img src="https://mintcdn.com/hobbyist-e43fa225/_qpHdwibkfCcXaky/images/new-foundry.png?fit=max&auto=format&n=_qpHdwibkfCcXaky&q=85&s=1338a0cf43c92807e8bcccdd0223d052" width="184" height="36" data-path="images/new-foundry.png" />
      </Note>

      You can use [new Foundry](https://ai.azure.com/) to:

      * Detect the language of input text
      * Review confidence scores and ISO language codes
      * Configure country/region hints for improved accuracy

      ## Navigate to the new Foundry playground

      The active project appears in the upper-left corner. To create a new project:

      1. Open the project drop-down menu.
      2. Enter a project name or select an existing one.
      3. Select **Create project**.

      <Frame>
        <img src="https://mintcdn.com/hobbyist-e43fa225/oqzVjT1qBo5Rp-96/images/new-foundry-homepage.png?fit=max&auto=format&n=oqzVjT1qBo5Rp-96&q=85&s=4a9e14bf35219604cca59cc0fa13bf26" alt="Screenshot of the new Foundry homepage" width="2717" height="1163" data-path="images/new-foundry-homepage.png" />
      </Frame>

      There are two ways to access the Language Detection interface:

      1. Select the **Discover** tab from the upper right navigation bar to go to the **Models** page.
         * In the search bar under models, enter **Azure** and press enter.
         * Next, select **Azure-Language-detection** from the search results.
         * Finally, select the **Open in Playground** button.

      2. Select the **Build** tab from the upper right navigation bar.
         * From the left navigation bar, select  **Models**.
         * Select the **AI services** tab.
         * Next, select  **Azure-Language-detection** to go to the playground.

      ## Detect language in the Foundry playground

      The **Detect Language** feature identifies the language used in written content.

      1. On the **Playground** tab, select a text sample from the drop-down menu, use the paperclip icon to upload your text, or enter your own text.

      2. Select the **Configure** button. In the **Configure** side panel, set the following options:

      | Option                             | Description                                                   |
      | ---------------------------------- | ------------------------------------------------------------- |
      | **API version**                    | Select the API version that you prefer to use.                |
      | **Model version**                  | Select the model version that you prefer to use.              |
      | **Country/region hint** (optional) | You can select the origin country/region for the source text. |

      After you make your selections, choose the **Detect** button. Then review the text and accompanying details written in formatted text or as a JSON response:

      | Field                    | Description                                                                          |
      | ------------------------ | ------------------------------------------------------------------------------------ |
      | **Confidence**           | The model's level of certainty regarding whether it correctly identified a language. |
      | **ISO 639-1 code**       | A two letter code for the detected language.                                         |
      | **Detected script**      | The name of the detected script in the text.                                         |
      | **Detected script code** | The ISO 15924 script code for the detected script (writing system).                  |

      Verify that the detected language matches the language of your input text. You can use the **Edit** button to modify the **Configure** parameters and rerun detection as needed.

      ## Open in Visual Studio Code 🆕

      After validating your scenario in the playground, select **Open in VS Code** to carry your current configuration directly into a development environment—no manual setup required.

      1. Configure your scenario in the playground:
         * Select your API version and model version.
         * Enter and test your sample input.
         * Adjust options such as API version, model version, and country/region hint.
      2. Select **Open in VS Code**.
      3. Visual Studio Code opens with a preconfigured code sample that reflects your playground configuration, including your API version, model, and language detection settings.

      <Tip>
        Use the playground to compare outputs across API versions—for example, preview versus GA—before exporting your configuration to code.
      </Tip>
    </Tab>
  </Tabs>
</ZoneContent>

## Troubleshooting

| Issue                                                 | Resolution                                                                                                                                                |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| You get a `401` or `403` error when calling the API.  | Confirm your key and endpoint are correct for the same Azure AI resource. If you recently changed role assignments, wait a few minutes and try again.     |
| You get an error about missing environment variables. | Confirm `LANGUAGE_KEY` and `LANGUAGE_ENDPOINT` are set in your environment before you run the sample.                                                     |
| The Foundry experience doesn't match the steps.       | In the Foundry portal, use the version toggle to switch between Foundry (classic) and Foundry (new), then follow the matching tab in the Foundry section. |
| The API returns `unknown` as the detected language.   | The input text might be too short or ambiguous. Provide a longer text sample or set the **Country/region hint** to improve accuracy.                      |
| The API returns an `InvalidCountryHint` error.        | Confirm the country/region hint code is a valid ISO 3166-1 alpha-2 code (for example, `US`, `FR`, `JP`).                                                  |

## Clean up resources

If you no longer need the resources you created in this quickstart, delete the individual resource or the entire resource group. Deleting the resource group also deletes all other resources associated with it.

* [Azure portal](../../multi-service-resource)
* [Azure CLI](../../multi-service-resource)

## Related content

* [Language detection overview](overview)
* [Call the Language Detection API](how-to/call-api)
* [Language support](language-support)
* [Use containers](how-to/use-containers)
