How to use @azure/ms-rest-js - 10 common examples

To help you get started, we’ve selected a few @azure/ms-rest-js examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Azure-Samples / cognitive-services-quickstart-code / javascript / Face / FaceQuickstart.js View on Github external
console.log("---------------------------------")
    console.log("SNAPSHOT")
    // Authenticate 2, need an additional (target) client for this example.
    let sourceClient = client // renaming to be relevent to this example

    // Your general Azure subscription ID is needed for this example only.
    // Since we are moving a person group from one region to another in the same
    // subscription, our source ID and target ID are the same.
    // Add your subscription ID (not to be confused with a subscription key) to your
    // environment variables. Find in the Azure portal on your Face overview page.
    let subscriptionID = process.env['AZURE_SUBSCRIPTION_ID']

    // Add a 2nd Face subscription key to your environment variables. Make sure the
    // 2nd set of key and endpoint is in the region or subscription you want to
    // transfer to.
    let credentials2 = new msRest.ApiKeyCredentials({
        inHeader: { 'Ocp-Apim-Subscription-Key': process.env['FACE_SUBSCRIPTION_KEY2'] }
    });
    let targetClient = new Face.FaceClient(credentials2, process.env['FACE_ENDPOINT2']);

    // Take the snapshot from your source region or Face subscription
    console.log('Taking the snapshot.')
    let takeOperationId = null
    await sourceClient.snapshot.take('PersonGroup', PERSON_GROUP_ID, [subscriptionID])
        .then((takeResponse) => {
            // Get the operation ID at the end of the response URL operation location
            takeOperationId = takeResponse.operationLocation.substring(takeResponse.operationLocation.lastIndexOf('/') + 1)
            console.log('Operation ID (take): ' + takeOperationId)
        }).catch((err) => {
            console.log(err)
            throw err
        })
github Azure / azure-sdk-for-js / sdk / keyvault / keyvault-secrets / samples / secrets.pipeline.ts View on Github external
} catch (e) {
    if (e instanceof RestError) {
      console.log("Rest Error: ", e.message);
    } else {
      throw e;
    }
  }

  // The client can also be configured using a a customized Pipeline. This allows control
  // over the request policy factories( for example, adding your own RequestPolicyFactory),
  // as well as providng a custom-implementation of HTTP Client.
  // This is a more advanced scenario. For more information, see
  // https://github.com/Azure/ms-rest-js/blob/master/docs/architectureOverview.md
  const customPipeline: Pipeline = {
    requestPolicyFactories: [
      deserializationPolicy(),
      exponentialRetryPolicy(),
      signingPolicy(credential),
    ]
  };
  const client2 = new SecretsClient(url, credential, customPipeline);

  for await (const version of client2.getSecretVersions(secretName)) {
    const secret = await client2.getSecret(secretName, { version: version.version });
    console.log("secret: ", secret);
  }

  await client.deleteSecret(secretName);
}
github Azure / ms-rest-nodeauth / samples / getCredentialsFromAzureCli.ts View on Github external
async function listResourceGroups(creds: AzureCliCredentials): Promise {
  function getUrl(subscriptionId: string): string {
    return `https://management.azure.com/subscriptions/${subscriptionId}/resourcegroups?api-version=2018-05-01`;
  }
  try {
    console.log(">>>>>>> List Resource groups <<<<<<<<<<<");
    // Setting the resource to ARM endpoint.
    creds.resource = "https://management.azure.com";
    const client = new ServiceClient(creds);
    console.log(">>> Subscription associated with the access token: '%s'.",
      creds.tokenInfo.subscription);
    const request: RequestPrepareOptions = {
      url: getUrl(creds.subscriptionInfo.id),
      method: "GET"
    };
    console.log(">>> Request url: '%s'.", request.url);
    const res = await client.sendRequest(request);
    console.log("List of resource groups from subscriptionId '%s': \n%O",
      creds.subscriptionInfo.id, res.parsedBody);

    // Let us change the subscriptionId, which should trigger refreshing the access token.
    const subscriptions = await AzureCliCredentials.listAllSubscriptions();
    creds.subscriptionInfo = subscriptions[1];
    console.log(">>> The new subscription id associated with the credential object is: '%s'.",
      creds.subscriptionInfo.id);
github Azure / azure-sdk-for-js / sdk / keyvault / keyvault-secrets / samples / secrets.pipeline.ts View on Github external
console.log("Rest Error: ", e.message);
    } else {
      throw e;
    }
  }

  // The client can also be configured using a a customized Pipeline. This allows control
  // over the request policy factories( for example, adding your own RequestPolicyFactory),
  // as well as providng a custom-implementation of HTTP Client.
  // This is a more advanced scenario. For more information, see
  // https://github.com/Azure/ms-rest-js/blob/master/docs/architectureOverview.md
  const customPipeline: Pipeline = {
    requestPolicyFactories: [
      deserializationPolicy(),
      exponentialRetryPolicy(),
      signingPolicy(credential),
    ]
  };
  const client2 = new SecretsClient(url, credential, customPipeline);

  for await (const version of client2.getSecretVersions(secretName)) {
    const secret = await client2.getSecret(secretName, { version: version.version });
    console.log("secret: ", secret);
  }

  await client.deleteSecret(secretName);
}
github Azure / azure-sdk-for-js / sdk / keyvault / keyvault-secrets / samples / secrets.pipeline.ts View on Github external
if (e instanceof RestError) {
      console.log("Rest Error: ", e.message);
    } else {
      throw e;
    }
  }

  // The client can also be configured using a a customized Pipeline. This allows control
  // over the request policy factories( for example, adding your own RequestPolicyFactory),
  // as well as providng a custom-implementation of HTTP Client.
  // This is a more advanced scenario. For more information, see
  // https://github.com/Azure/ms-rest-js/blob/master/docs/architectureOverview.md
  const customPipeline: Pipeline = {
    requestPolicyFactories: [
      deserializationPolicy(),
      exponentialRetryPolicy(),
      signingPolicy(credential),
    ]
  };
  const client2 = new SecretsClient(url, credential, customPipeline);

  for await (const version of client2.getSecretVersions(secretName)) {
    const secret = await client2.getSecret(secretName, { version: version.version });
    console.log("secret: ", secret);
  }

  await client.deleteSecret(secretName);
}
github Azure-Samples / cognitive-services-quickstart-code / javascript / LUIS / luis_prediction.js View on Github external
const key = process.env["LUIS_RUNTIME_KEY"];
if (!key) {
    throw new Error(
        "Set/export your LUIS runtime key as an environment variable."
    );
}

const endpoint = process.env["LUIS_RUNTIME_ENDPOINT"];
if (!endpoint) {
    throw new Error("Set/export your LUIS runtime endpoint as an environment variable.");
}
// 

// 
const luisRuntimeClient = new LUIS.LUISRuntimeClient(
    new msRest.ApiKeyCredentials({
        inHeader: { "Ocp-Apim-Subscription-Key": key }
    }),
    endpoint
);
// 

// 
// Use public app ID or replace with your own trained and published app's ID
// to query your own app
// public appID = `df67dcdb-c37d-46af-88e1-8b97951ca1c2`
// with slot of `production`
const luisAppID = process.env['LUIS_APP_ID'];
if (!luisAppID) {
    throw new Error(
        "Set/export your LUIS app ID as an environment variable."
    );
github microsoft / botbuilder-tools / packages / LUIS / bin / luis.js View on Github external
let json = await stdin();
        serviceIn = JSON.parse(json);
    }

    args.authoringKey = args.authoringKey || serviceIn.authoringKey || config.authoringKey;
    args.subscriptionKey = args.subscriptionKey || args.s || serviceIn.subscriptionKey || config.subscriptionKey;
    args.appId = args.appId || args.applicationId || args.a || serviceIn.appId || config.appId;
    args.versionId = args.versionId || args.version || serviceIn.versionId || config.versionId || serviceIn.version;
    args.region = args.region || serviceIn.region || config.region || "westus";
    args.cloud = args.cloud || serviceIn.cloud || config.cloud || (args.region == "virginia" ? "us" : "com");
    args.customHeaders = { "accept-language": "en-US" };
    args.endpoint = args.endpoint || serviceIn.endpoint || config.endpoint || `https://${args.region}.api.cognitive.microsoft.${args.cloud}`;

    validateConfig(args);

    let credentials = new msRest.ApiKeyCredentials({ inHeader: { "Ocp-Apim-Subscription-Key": args.authoringKey } });
    const client = new LuisAuthoring(args.endpoint, credentials);

    // NOTE: This should not be necessary to do. It is required because the swagger file defines a template of
    // x-ms-parameterized-host/hostTemplate: "{Endpoint}/luis/api/v2.0" which does not seem to be picked up
    // properly by autorest.  In particular the baseUri on the client is just "{Endpoint}" and the operations
    // assume the presence of luis/api/v2.0 so you are missing the middle part of the URL.
    // Instead of using autorest here, we should be using the officially supported client and that client
    // should take in the full authoring endpoint.
    client.baseUri = `{Endpoint}/luis/api/v2.0`;

    // special non-operation commands
    switch (args._[0]) {
        case "query":
            return await handleQueryCommand(args, config);
        case "set":
            return await handleSetCommand(args, config, client);
github Azure-Samples / cognitive-services-quickstart-code / javascript / QnAMaker / sdk / qnamaker_quickstart.js View on Github external
// 
    const creds = new msRest.ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': subscription_key } });
    const qnaMakerClient = new qnamaker.QnAMakerClient(creds, endpoint);
    const knowledgeBaseClient = new qnamaker.Knowledgebase(qnaMakerClient);
    // 

    const knowledgeBaseID = await createKnowledgeBase(qnaMakerClient, knowledgeBaseClient);
    await updateKnowledgeBase(qnaMakerClient, knowledgeBaseClient, knowledgeBaseID);
    await publishKnowledgeBase(knowledgeBaseClient, knowledgeBaseID);
    await downloadKnowledgeBase(knowledgeBaseClient, knowledgeBaseID)
    const primaryQueryRuntimeKey = await getEndpointKeys(qnaMakerClient);

    await listKnowledgeBasesInResource(knowledgeBaseClient)

    // 
    const queryRutimeCredentials = new msRest.ApiKeyCredentials({ inHeader: { 'Authorization': 'EndpointKey ' + primaryQueryRuntimeKey } });
    const runtimeClient = new qnamaker_runtime.QnAMakerRuntimeClient(queryRutimeCredentials, runtime_endpoint);
    // 

    await generateAnswer(runtimeClient, primaryQueryRuntimeKey, knowledgeBaseID)
    await deleteKnowledgeBase(knowledgeBaseClient, knowledgeBaseID)
}
// 
github Azure-Samples / cognitive-services-quickstart-code / javascript / LUIS / node-sdk-authoring-prediction / luis_prediction.js View on Github external
// 
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-runtime");
// 

// 
const key = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY"

const endpoint = "https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.com"
// 

// 
const luisRuntimeClient = new LUIS.LUISRuntimeClient(
    new msRest.ApiKeyCredentials({
        inHeader: { "Ocp-Apim-Subscription-Key": key }
    }),
    endpoint
);
// 

// 
// Use public app ID or replace with your own trained and published app's ID
// to query your own app
// public appID = `df67dcdb-c37d-46af-88e1-8b97951ca1c2`
// with slot of `production`
const luisAppID = "REPLACE-WITH-YOUR-LUIS_APP_ID"

// `production` or `staging`
const luisSlotName = "production"
// 
github Azure-Samples / cognitive-services-quickstart-code / javascript / ComputerVision / ComputerVisionQuickstart.js View on Github external
* Generate Thumbnail, Batch Read File, Recognize Text (OCR), Recognize Printed & Handwritten Text.
 */

// 
/**
 * AUTHENTICATE
 * This single client is used for all examples.
 */
let key = process.env['COMPUTER_VISION_SUBSCRIPTION_KEY'];
let endpoint = process.env['COMPUTER_VISION_ENDPOINT']
if (!key) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
// 

// 
let computerVisionClient = new ComputerVisionClient(
    new ApiKeyCredentials({inHeader: {'Ocp-Apim-Subscription-Key': key}}), endpoint);
// 
/**
 * END - Authenticate
 */

// 
function computerVision() {
  async.series([
    async function () {
      // 

      /**
       * DESCRIBE IMAGE
       * Describes what the main objects or themes are in an image.
       * Describes both a URL and a local image.
       */