### TenantItemsClient Usage Examples Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/test/unittest/scenarios/tenant-resource.md Examples demonstrating how to initialize the client and perform Get and List operations for tenant-scoped resources. ```go // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package testmodule_test import ( "context" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "log" "testmodule" ) // Generated from example definition: TenantItems_get.json func ExampleTenantItemsClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := testmodule.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewTenantItemsClient().Get(ctx, "2025-01-01", "myTenantItem", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res = testmodule.TenantItemsClientGetResponse{ // TenantItem: testmodule.TenantItem{ // ID: to.Ptr("/providers/Microsoft.Test/tenantItems/myTenantItem"), // Name: to.Ptr("myTenantItem"), // Type: to.Ptr("Microsoft.Test/tenantItems"), // Properties: &testmodule.TenantItemProperties{ // Description: to.Ptr("my tenant item"), // ProvisioningState: to.Ptr(testmodule.ProvisioningStateSucceeded), // }, // }, // } } // Generated from example definition: TenantItems_list.json func ExampleTenantItemsClient_NewListPager() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := testmodule.NewClientFactory("", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } pager := clientFactory.NewTenantItemsClient().NewListPager("2025-01-01", nil) for pager.More() { page, err := pager.NextPage(ctx) if err != nil { log.Fatalf("failed to advance page: %v", err) } for _, v := range page.Value { // You could use page here. We use blank identifier for just demo purposes. _ = v } // If the HTTP response code is 200 as defined in example definition, your page structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // page = testmodule.TenantItemsClientListResponse{ // TenantItemListResult: testmodule.TenantItemListResult{ // Value: []*testmodule.TenantItem{ // { // ID: to.Ptr("/providers/Microsoft.Test/tenantItems/myTenantItem"), // Name: to.Ptr("myTenantItem"), // Type: to.Ptr("Microsoft.Test/tenantItems"), // Properties: &testmodule.TenantItemProperties{ // Description: to.Ptr("my tenant item"), // ProvisioningState: to.Ptr(testmodule.ProvisioningStateSucceeded), // }, // }, // }, // }, // } } } ``` -------------------------------- ### AutoRest Info Output Example Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-java/docs/developer/readme.md Example output showing installed AutoRest CLI, Core, and extension versions. ```text AutoRest code generation utility [cli version: 3.3.2; node: v12.16.1] (C) 2018 Microsoft Corporation. https://aka.ms/autorest Showing All Installed Extensions Type Extension Name Version Location core @autorest/core 3.4.5 C:\Users\\.autorest\@autorest_core@3.4.5 core @autorest/core 3.5.1 C:\Users\\.autorest\@autorest_core@3.5.1 extension @autorest/java 4.0.30 C:\Users\\.autorest\@autorest_java@4.0.30 extension @autorest/modelerfour 4.18.1 C:\Users\\.autorest\@autorest_modelerfour@4.18.1 extension @autorest/modelerfour 4.19.3 C:\Users\\.autorest\@autorest_modelerfour@4.19.3 ``` -------------------------------- ### Install the package Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-autorest-canonical/README.md Install the library using npm. ```bash npm install @azure-tools/typespec-autorest-canonical ``` -------------------------------- ### @example Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-autorest/README.md The @example decorator attaches example files to an operation. Multiple examples can be specified. ```APIDOC ## @example ### Description Attaches example files to an operation. Multiple examples can be specified. ### Signature `@Autorest.example(pathOrUri: valueof string, title: valueof string)` ### Target Operation ### Parameters - **pathOrUri** (valueof string) - Required - Path or Uri to the example file. - **title** (valueof string) - Required - Name or description of the example file. ``` -------------------------------- ### Install the package Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-java/README.md Install the emitter package using npm. ```bash npm install @azure-tools/typespec-java ``` -------------------------------- ### Install dependencies Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/migrate-swagger/01-get-started.md Run this command at the root of the repository to install necessary dependencies. ```shell npm install # Run at root of the repository ``` -------------------------------- ### API Operation Examples Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/test/unittest/scenarios/body-root.md JSON examples for BodyRoots operations including action, get, and put requests. ```json { "operationId": "BodyRoots_action", "title": "BodyRoots_action", "parameters": { "api-version": "2025-01-01", "subscriptionId": "00000000-0000-0000-0000-000000000000", "resourceGroupName": "myResourceGroup", "bodyRootName": "myBodyRoot", "filter": "constantValue", "action": { "prop": "myProp" } }, "responses": { "204": {} } } ``` ```json { "operationId": "BodyRoots_get", "title": "BodyRoots_get_with_availability", "parameters": { "api-version": "2025-01-01", "subscriptionId": "00000000-0000-0000-0000-000000000000", "resourceGroupName": "myResourceGroup", "bodyRootName": "myBodyRoot" }, "responses": { "200": { "body": { "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Test/bodyRoots/myBodyRoot", "name": "myBodyRoot", "type": "Microsoft.Test/bodyRoots", "location": "eastus", "properties": { "description": "my body root", "provisioningState": "Succeeded", "availability": { "isPreview": true, "status": 1 } } } } } } ``` ```json { "operationId": "BodyRoots_put", "title": "BodyRoots_put_with_availability", "parameters": { "api-version": "2025-01-01", "subscriptionId": "00000000-0000-0000-0000-000000000000", "resourceGroupName": "myResourceGroup", "bodyRootName": "myBodyRoot", "resource": { "location": "eastus", "properties": { "description": "my body root", "availability": { "isPreview": true, "status": 1 } } } }, "responses": { "200": { "body": { "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Test/bodyRoots/myBodyRoot", "name": "myBodyRoot", "type": "Microsoft.Test/bodyRoots", "location": "eastus", "properties": { "description": "my body root", "provisioningState": "Succeeded", "availability": { "isPreview": true, "status": 1 } } } }, "201": { "body": { "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Test/bodyRoots/myBodyRoot", "name": "myBodyRoot", "type": "Microsoft.Test/bodyRoots", "location": "eastus", "properties": { "description": "my body root", "provisioningState": "Succeeded", "availability": { "isPreview": true, "status": 1 } } } } } } ``` -------------------------------- ### Run AutoRest Test Server locally Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-java/docs/developer/readme.md Commands to install dependencies and start the test server for integrated testing. ```bash npm install npm run testserver-run ``` -------------------------------- ### Install development tools Source: https://github.com/azure/typespec-azure/blob/main/CONTRIBUTING.md Use mise and pnpm to install the required tool versions defined in the repository configuration. ```bash mise install pnpm install ``` -------------------------------- ### Operation Example Inputs Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/test/unittest/scenarios/polymorphic.md JSON examples for the adoptCat and adoptPet operations. ```json { "operationId": "Pets_adoptCat", "title": "Pets_adoptCat", "parameters": { "api-version": "2025-01-01", "subscriptionId": "00000000-0000-0000-0000-000000000000", "resourceGroupName": "myResourceGroup", "petResourceName": "myPetResource", "cat": { "kind": "Cat", "name": "Whiskers", "purrs": true } }, "responses": { "200": { "body": { "kind": "Cat", "name": "Whiskers", "purrs": true } } } } ``` ```json { "operationId": "Pets_adoptPet", "title": "Pets_adoptPet", "parameters": { "api-version": "2025-01-01", "subscriptionId": "00000000-0000-0000-0000-000000000000", "resourceGroupName": "myResourceGroup", "petResourceName": "myPetResource", "pet": { "kind": "Dog", "name": "Buddy", "breed": "Labrador" } }, "responses": { "200": { "body": { "kind": "Dog", "name": "Buddy", "breed": "Labrador" } } } } ``` -------------------------------- ### Rename Examples Directory Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/howtos/Versioning/02-preview-after-preview.md Update the examples folder path to match the new API version. ```bash > mv examples/2025-12-01-preview examples/2026-01-01-preview ``` -------------------------------- ### Install dependencies Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/docs/development.md Install all required project dependencies using pnpm. ```terminal pnpm install ``` -------------------------------- ### Install the emitter Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/README.md Use npm to install the @azure-tools/typespec-go package. ```bash npm install @azure-tools/typespec-go ``` -------------------------------- ### Generated Client Usage Examples Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/howtos/Generate client libraries/03client.mdx Examples of how to instantiate and use the generated sub clients across different programming languages. ```python # generated _client.py class PetStoreClient: def __init__(self, endpoint: str, **kwargs: Any) -> None: ... # generated operations/_operations.py class OpGrp1Operations: @distributed_trace def feed(self, **kwargs: Any) -> None: class OpGrp2Operations: @distributed_trace def pet(self, **kwargs: Any) -> None: #usage sample from pet_store_renamed import PetStoreClient client = PetStoreClient() client.op_grp_1.feed() client.op_grp_2.pet() ``` ```csharp using PetStoreRenamed; PetStoreClient client = new PetStoreClient(); client.GetOpGrp1Client().Feed(); client.GetOpGrp2Client().Pet(); ``` ```typescript import { PetStoreClient } from "@azure/package-name"; const client = new PetStoreClient(); client.opGrp1.feed(); client.opGrp2.pet(); ``` ```java // Client builder class package petstorerenamed; @ServiceClientBuilder( serviceClients = { OpGrp1Client.class, OpGrp2Client.class, OpGrp1AsyncClient.class, OpGrp2AsyncClient.class }) public final class PetStoreClientBuilder implements HttpTrait, ConfigurationTrait, EndpointTrait { public OpGrp1Client buildOpGrp1Client(); public OpGrp2Client buildOpGrp2Client(); } // Client class @ServiceClient(builder = PetStoreClientBuilder.class) public final class OpGrp1Client { public void feed(); } @ServiceClient(builder = PetStoreClientBuilder.class) public final class OpGrp2Client { public void pet(); } // Usage package petstorerenamed; PetStoreClientBuilder builder = new PetStoreClientBuilder(); OpGrp1Client opGrp1Client = builder.buildOpGrp1Client(); opGrp1Client.feed(); OpGrp2Client opGrp2Client = builder.buildOpGrp2Client(); opGrp2Client.pet(); ``` ```go // generated petstore_client.go type PetStoreClient struct {} func NewPetStoreClient() *PetStoreClient{ return &PetStoreClient{} } func (client *PetStoreClient)NewOpGrp1Client() *OpGrp1Client{ return &OpGrp1Client{} } func (client *PetStoreClient)NewOpGrp2Client() *OpGrp2Client{ return &OpGrp2Client{} } // generated petstoreopgrp1_client.go type OpGrp1Client struct {} func (client *PetStoreOpGrp1Client) Feed(ctx context.Context, options *PetStoreOpGrp1ClientFeedOptions) (PetStoreOpGrp1ClientFeedResponse, error) {} // generated petstoreopgrp2_client.go type OpGrp2Client struct {} func (client *PetStoreOpGrp2Client) Pet(ctx context.Context, options *PetStoreOpGrp2ClientPetOptions) (PetStoreOpGrp2ClientPetResponse, error) {} // generated options.go type PetStoreOpGrp1ClientFeedOptions struct {} type PetStoreOpGrp2ClientPetOptions struct {} // generated response.go type PetStoreOpGrp1ClientFeedResponse struct {} type PetStoreOpGrp2ClientPetResponse struct {} // Usage Sample petStoreClient := NewPetStoreClient() opGrp1Client := petStoreClient.NewOpGrp1Client() opGrp1Client.Feed(context.Background(), &PetStoreOpGrp1ClientFeedOptions{}) opGrp2Client := petStoreClient.NewOpGrp2Client() opGrp2Client.Pet(context.Background(),&PetStoreOpGrp2ClientPetOptions{}) ``` -------------------------------- ### Install the package Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-autorest/README.md Use npm to install the @azure-tools/typespec-autorest package. ```bash npm install @azure-tools/typespec-autorest ``` -------------------------------- ### Generate examples using OAV Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/migrate-swagger/faq/x-ms-examples.mdx Command to generate initial example files from an OpenAPI specification. ```bash oav generate-examples openapi.json ``` -------------------------------- ### Alias ExternalResource examples Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/libraries/azure-resource-manager/reference/data-types.md Examples showing how to alias external resources. ```typespec alias VirtualMachine = ExternalResource<"Microsoft.Compute", "virtualMachines", "vmName">; ``` ```typespec alias Scaleset = Extension.ExternalResource< "Microsoft.Compute", "virtualMachineScaleSets", "scaleSetName" >; ``` -------------------------------- ### Install @azure-tools/typespec-azure-portal-core Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-azure-portal-core/README.md Install the TypeSpec Azure Portal Core library using npm. ```bash npm install @azure-tools/typespec-azure-portal-core ``` -------------------------------- ### Generated client library documentation examples Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/howtos/Generate client libraries/08types.mdx These examples show how the @clientDoc decorator manifests in various target languages. ```python class Point(_model_base.Model): """Represents a position in a 2D coordinate system. :param x: The horizontal position (increases moving right) :type x: float :param y: The vertical position (increases moving down) :type y: float """ x: float = rest_field() """The horizontal position (increases moving right).""" y: float = rest_field() """The vertical position (increases moving down).""" class Shape(_model_base.Model): """Base class for all shape objects that can be drawn on a canvas. :param position: The x,y coordinates where the shape will be positioned on the canvas :type position: Point """ position: Point = rest_field() """The x,y coordinates where the shape will be positioned on the canvas.""" ``` ```csharp /// /// Base class for all shape objects that can be drawn on a canvas /// public partial class Shape { /// /// The x,y coordinates where the shape will be positioned on the canvas /// public Point Position { get; set; } } /// /// Represents a position in a 2D coordinate system /// public partial class Point { /// /// The horizontal position (increases moving right) /// public float X { get; set; } /// /// The vertical position (increases moving down) /// public float Y { get; set; } } ``` ```typescript /** * Base class for all shape objects that can be drawn on a canvas */ export interface Shape { /** * The x,y coordinates where the shape will be positioned on the canvas */ position: Point; } /** * Represents a position in a 2D coordinate system */ export interface Point { /** * The horizontal position (increases moving right) */ x: number; /** * The vertical position (increases moving down) */ y: number; } ``` -------------------------------- ### Install TypeSpec Project Dependencies Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/getstarted/createproject.md After creating a new project, run this command to install the necessary dependencies. Use `npm ci` if your project is within the `azure-rest-api-specs` repository, otherwise use `tsp install`. ```bash tsp install ``` -------------------------------- ### Check AutoRest Installation Info Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-java/docs/developer/readme.md Run this command to view installed extensions and their versions. ```bash autorest --info ``` -------------------------------- ### Initialize Client with Sub-Client (Same Parameters) Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-client-generator-core/design-docs/client.md Shows how to initialize a client and then obtain a sub-client that shares the same initialization parameters. ```Python client = TestClient(endpoint="endpoint", credential=AzureKeyCredential("key")) client.do_something() sub_client = client.sub_client() sub_client.do_something() ``` -------------------------------- ### Client Usage Sample Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-ts/test/modular-unit/scenarios/samples/parameters/clientConstructorArgs.md Demonstrates how to instantiate the client with required parameters and execute an operation. ```ts /** This file path is /samples-dev/createOrUpdateSample.ts */ import { MachineLearningServicesClient } from "@azure/internal-test"; import { DefaultAzureCredential } from "@azure/identity"; /** * This sample demonstrates how to execute createOrUpdate * * @summary execute createOrUpdate * x-ms-original-file: 2021-10-01-preview/json_for_Indexes_CreateOrUpdate.json */ async function indexesCreateOrUpdate(): Promise { const endpoint = process.env.MACHINE_LEARNING_SERVICES_ENDPOINT || ""; const subscriptionId = process.env.MACHINE_LEARNING_SERVICES_SUBSCRIPTION_ID || ""; const resourceGroupName = process.env.MACHINE_LEARNING_SERVICES_RESOURCE_GROUP_NAME || ""; const workspaceName = process.env.MACHINE_LEARNING_SERVICES_WORKSPACE_NAME || ""; const credential = new DefaultAzureCredential(); const client = new MachineLearningServicesClient( endpoint, subscriptionId, resourceGroupName, workspaceName, credential, ); await client.createOrUpdate("test-index", "1"); } async function main(): Promise { await indexesCreateOrUpdate(); } main().catch(console.error); ``` -------------------------------- ### Generated Client Usage Examples Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/howtos/Generate client libraries/03client.mdx Examples of how the customized client hierarchy appears and is used across different programming languages. ```python # generated _client.py class PetStoreClient(_PetStoreClientOperationsMixin): def __init__(self, endpoint: str, **kwargs: Any) -> None: ... # generated _operations/_operations.py class _PetStoreClientOperationsMixin: @distributed_trace def feed(self, **kwargs: Any) -> None: @distributed_trace def pet(self, **kwargs: Any) -> None: #usage sample from pet_store import PetStoreClient client = PetStoreClient() client.feed() client.pet() ``` ```csharp using PetStore; PetStoreClient client = new PetStoreClient(); client.Feed(); client.Pet(); ``` ```typescript import { PetStoreClient } from "@azure/package-name"; const client = new PetStoreClient(); client.feed(); client.pet(); ``` ```java // Client builder class package petstore; @ServiceClientBuilder(serviceClients = { PetStoreClient.class, PetStoreAsyncClient.class }) public final class PetStoreClientBuilder implements HttpTrait, ConfigurationTrait, EndpointTrait { public PetStoreClientBuilder(); public PetStoreClient buildClient(); } // Client class @ServiceClient(builder = PetStoreClientBuilder.class) public final class PetStoreClient { public void feed(); public void pet(); } // Usage PetStoreClient client = new PetStoreClientBuilder().buildClient(); client.feed(); client.pet(); ``` ```go // generated petstore_client.go type PetStoreClient struct {} func NewPetStoreClient() *PetStoreClient{ return &PetStoreClient{} } func (client *PetStoreClient) Feed(ctx context.Context, options *PetStoreClientFeedOptions) (PetStoreClientFeedResponse, error) {} func (client *PetStoreClient) Pet(ctx context.Context, options *PetStoreClientPetOptions) (PetStoreClientPetResponse, error) {} // generated options.go type PetStoreClientFeedOptions struct {} type PetStoreClientPetOptions struct {} // generated response.go type PetStoreClientFeedResponse struct {} type PetStoreClientPetResponse struct {} // Usage Sample petStoreClient := NewPetStoreClient() petStoreClient.Feed(context.Background(), &PetStoreClientFeedOptions{}) petStoreClient.Pet(context.Background(), &PetStoreClientPetOptions{}) ``` -------------------------------- ### Usage Sample for Generated Clients Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/howtos/Generate client libraries/03client.mdx Demonstrates how to instantiate and call methods on the generated pet store clients. ```go petStoreClient := NewPetStoreClient() petStoreClient.Info(context.Background(), &PetStoreClientInfoOptions{}) petStoreActionsClient := NewPetStoreActionsClient() petStoreActionsClient.Close(context.Background(), &PetStoreActionsClientCloseOptions{}) petStoreActionsClient.Open(context.Background(), &PetStoreActionsClientOpenOptions{}) petStoreBillingsClient := NewPetStoreBillingsClient() petStoreBillingsClient.History(context.Background(), &PetStoreBillingsClientHistoryOptions{}) petStorePetsClient := NewPetStorePetsClient() petStorePetsClient.Info(context.Background(), &PetStorePetsClientInfoOptions{}) petStorePetsActionsClient := NewPetStorePetsActionsClient() petStorePetsActionsClient.Feed(context.Background(), &PetStorePetsActionsClientFeedOptions{}) petStorePetsActionsClient.Pet(context.Background(), &PetStorePetsActionsClientPetOptions{}) ``` -------------------------------- ### MixedScopeWidgets Get Example Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/test/unittest/scenarios/tenant-resource.md JSON payload for the MixedScopeWidgets_Get operation. ```json { "operationId": "MixedScopeWidgets_Get", "title": "MixedScopeWidgets_get", "parameters": { "api-version": "2025-01-01", "subscriptionId": "00000000-0000-0000-0000-000000000000", "resourceGroupName": "myResourceGroup", "widgetName": "myWidget" }, "responses": { "200": { "body": { "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Test/mixedScopeWidgets/myWidget", "name": "myWidget", "type": "Microsoft.Test/mixedScopeWidgets", "location": "eastus", "properties": { "description": "my widget", "provisioningState": "Succeeded" } } } } } ``` -------------------------------- ### TenantItems Get Example Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/test/unittest/scenarios/tenant-resource.md JSON payload for the TenantItems_Get operation. ```json { "operationId": "TenantItems_Get", "title": "TenantItems_get", "parameters": { "api-version": "2025-01-01", "tenantItemName": "myTenantItem" }, "responses": { "200": { "body": { "id": "/providers/Microsoft.Test/tenantItems/myTenantItem", "name": "myTenantItem", "type": "Microsoft.Test/tenantItems", "properties": { "description": "my tenant item", "provisioningState": "Succeeded" } } } } } ``` -------------------------------- ### Client Usage Examples Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/howtos/Generate client libraries/10versioning.mdx Examples of how the extended API versions manifest in generated client libraries across different languages. ```python # The generated client accepts api_version as a keyword argument. # The API version defaults to the latest version "v5". client = ContosoClient(endpoint="...", api_version="v1") ``` ```csharp // The ServiceVersion enum includes all five versions. public enum ServiceVersion { V1 = 1, V2 = 2, V3 = 3, V4 = 4, V5 = 5, } ``` ```typescript export enum KnownClientApiVersions { V1 = "v1", V2 = "v2", V3 = "v3", V4 = "v4", V5 = "v5", } ``` ```java // NOT_SUPPORTED ``` ```go // NOT_SUPPORTED ``` -------------------------------- ### Correct ARM path casing example Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-azure-resource-manager/src/rules/arm-no-path-casing-conflicts.md This example demonstrates the compliant approach where segments are distinct. ```tsp model Foo is ProxyResource<{}> { @key("name") @path @segment("foos") @visibility(Lifecycle.Read) name: string; } model Bar is ProxyResource<{}> { @key("name") @path @segment("bars") @visibility(Lifecycle.Read) name: string; } ``` -------------------------------- ### Incorrect GET and DELETE operations with request bodies Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-azure-core/src/rules/rpc-operation-request-body.md These examples demonstrate invalid usage where a request body is defined for GET or DELETE operations. ```typespec @get op getWidget is RpcOperation< { @body body: Widget; }, Widget >; ``` ```typespec @delete op deleteWidget is RpcOperation< { @body body: Widget; }, Widget >; ``` -------------------------------- ### Build the project Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-ts/CONTRIBUTING.md Install dependencies and build the repository or specific packages. ```bash pnpm install pnpm build ``` ```bash pnpm -r --filter "@azure-tools/typespec-ts..." build ``` -------------------------------- ### Correct GET and DELETE operations without request bodies Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-azure-core/src/rules/rpc-operation-request-body.md These examples show the correct way to define GET and DELETE operations without a request body. ```typespec @get op getWidget is RpcOperation<{}, Widget>; ``` ```typespec @delete op deleteWidget is RpcOperation<{}, Widget>; ``` -------------------------------- ### Use customized authentication Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-java/docs/developer/2022-05-18-dpg-archboard-review.md Shows how to initialize a client builder with custom key credentials. ```java MetricsAdvisorAdministrationClientBuilder builder = new MetricsAdvisorAdministrationClientBuilder() .endpoint(getEndpoint()); builder.credential(new MetricsAdvisorKeyCredential("subscription_key", "api_key")); ``` -------------------------------- ### Define Model and Operation in TypeSpec Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-ts/test/modular-unit/scenarios/operations/wrapNonModelReturn.md Example of a model definition and a GET operation in TypeSpec. ```tsp model MyModel { name: string; } @route("/models") @get op getModel(): MyModel; ``` -------------------------------- ### Install Azure Core Library Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/libraries/azure-core/reference/index.mdx Commands to install the Azure Core library dependency for different project types. ```bash npm install @azure-tools/typespec-azure-core ``` ```bash npm install --save-peer @azure-tools/typespec-azure-core ``` -------------------------------- ### Execute Parameter Group Operations in Go Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/test/unittest/scenarios/parameter-groups.md Examples showing how to initialize a client factory and call operations with and without parameter groups. ```go // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package testmodule_test import ( "context" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "log" "testmodule" ) // Generated from example definition: ParameterGroupOperations_noParameterGroup.json func ExampleParameterGroupOperationsClient_NoParameterGroup() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := testmodule.NewClientFactory("00000000-0000-0000-0000-000000000000", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewParameterGroupOperationsClient().NoParameterGroup(ctx, "2025-01-01", "myResourceGroup", "myWidget", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res = testmodule.ParameterGroupOperationsClientNoParameterGroupResponse{ // Widget: testmodule.Widget{ // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Test/widgets/myWidget"), // Name: to.Ptr("myWidget"), // Type: to.Ptr("Microsoft.Test/widgets"), // Location: to.Ptr("eastus"), // Properties: &testmodule.WidgetProperties{ // Name: to.Ptr("myWidget"), // Description: to.Ptr("A test widget"), // }, // }, // } } // Generated from example definition: ParameterGroupOperations_queryParameterGroup.json func ExampleParameterGroupOperationsClient_QueryParameterGroup() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := testmodule.NewClientFactory("00000000-0000-0000-0000-000000000000", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewParameterGroupOperationsClient().QueryParameterGroup(ctx, "2025-01-01", "myResourceGroup", "myWidget", testmodule.TestQueryParams{FilterName: "myFilter"}, nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res = testmodule.ParameterGroupOperationsClientQueryParameterGroupResponse{ // Widget: testmodule.Widget{ // ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Test/widgets/myWidget"), // Name: to.Ptr("myWidget"), // Type: to.Ptr("Microsoft.Test/widgets"), // Location: to.Ptr("eastus"), // Properties: &testmodule.WidgetProperties{ // Name: to.Ptr("myWidget"), // Description: to.Ptr("A test widget"), // }, // }, // } } ``` -------------------------------- ### Force pageable behavior on an operation Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-client-generator-core/README.md Example of applying the markAsPageable decorator to a standard GET operation. ```typespec @Azure.ClientGenerator.Core.Legacy.markAsPageable @route("/items") @get op listItems(): ItemListResult; ``` -------------------------------- ### Correct ARM Action Verb Usage Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-azure-resource-manager/src/rules/arm-resource-invalid-action-verb.md Examples of valid operations using @post or @get. ```typespec op postAction is ArmProviderActionAsync< { name: string; }, ArmCombinedLroHeaders, SubscriptionActionScope >; ``` ```typespec @get op getAction is ArmProviderActionSync< { name: string; }, ArmCombinedLroHeaders, SubscriptionActionScope >; ``` -------------------------------- ### Correct Model and Interface Naming Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-azure-core/src/rules/casing-style.md Examples of models and interfaces that adhere to the casing style guide. ```tsp model Pet {} model PetFood {} ``` ```tsp model Pet { name: string; } ``` ```tsp op createPet(): void; ``` ```tsp interface PetStores {} ``` -------------------------------- ### Start Local Development Server Source: https://github.com/azure/typespec-azure/blob/main/website/README.md Use this command to start a local development server for live previewing changes. The server typically runs at `localhost:4321`. ```bash pnpm dev ``` ```bash pnpm start ``` -------------------------------- ### Incorrect Model and Interface Naming Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-azure-core/src/rules/casing-style.md Examples of models and interfaces that violate the casing style guide. ```tsp model pet {} model pet_food {} ``` ```tsp model Pet { Name: string; } ``` ```tsp op CreatePet(): void; ``` ```tsp interface petStores {} ``` -------------------------------- ### Example JSON for Employees_Get Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-ts/test/modular-unit/scenarios/test/operations/basicOperationTest.md Raw JSON payload representing a successful GET request for an Employee resource. ```json { "title": "Employees_Get", "operationId": "Employees_Get", "parameters": { "api-version": "2021-10-01-preview", "subscriptionId": "11809CA1-E126-4017-945E-AA795CD5C5A9", "resourceGroupName": "rgopenapi", "employeeName": "testEmployee" }, "responses": { "200": { "body": { "id": "/subscriptions/11809CA1-E126-4017-945E-AA795CD5C5A9/resourceGroups/rgopenapi/providers/Microsoft.Contoso/employees/testEmployee", "name": "testEmployee", "type": "Microsoft.Contoso/employees", "location": "eastus", "properties": { "age": 30, "city": "Seattle", "profile": "developer" }, "tags": { "environment": "test" } } } } } ``` -------------------------------- ### Initialize Development Environment Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/howtos/contributing/creating-linter-rules.md Commands to enable corepack, clone the repository with submodules, and install dependencies. ```bash corepack enable git clone --recurse-submodules https://github.com/Azure/typespec-azure.git cd typespec-azure pnpm install ``` -------------------------------- ### Incorrect ARM Action Verb Usage Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-azure-resource-manager/src/rules/arm-resource-invalid-action-verb.md Example of an invalid operation using @delete instead of @post or @get. ```typespec @delete op getAction is ArmProviderActionAsync< { name: string; }, ArmCombinedLroHeaders, SubscriptionActionScope >; ``` -------------------------------- ### Initialize Single Client Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-client-generator-core/design-docs/client.md Demonstrates the basic initialization of a single client with an endpoint and credentials. ```Python client = SingleClient(endpoint="endpoint", credential=AzureKeyCredential("key")) client.do_something() ``` -------------------------------- ### Configurations Client Streaming Operations Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-go/test/unittest/scenarios/streaming-response.md Examples demonstrating how to use the ConfigurationsClient to perform streaming and text-based operations. ```go // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. package testmodule_test import ( "bytes" "context" "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "log" "testmodule" ) // Generated from example definition: Configurations_getStreamingContent.json func ExampleConfigurationsClient_GetStreamingContent() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := testmodule.NewClientFactory("00000000-0000-0000-0000-000000000000", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewConfigurationsClient().GetStreamingContent(ctx, "2025-01-01", "myResourceGroup", "myConfiguration", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res = testmodule.ConfigurationsClientGetStreamingContentResponse{ // ContentType: to.Ptr("text/powershell"), // Body: io.NopCloser(bytes.NewReader([]byte("Configuration file content as a streaming response"))), // } } // Generated from example definition: Configurations_getTextContent.json func ExampleConfigurationsClient_GetTextContent() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := testmodule.NewClientFactory("00000000-0000-0000-0000-000000000000", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } res, err := clientFactory.NewConfigurationsClient().GetTextContent(ctx, "2025-01-01", "myResourceGroup", "myConfiguration", nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } // You could use response here. We use blank identifier for just demo purposes. _ = res // If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes. // res = testmodule.ConfigurationsClientGetTextContentResponse{ // Value: to.Ptr("config text"), // } } // Generated from example definition: Configurations_putStreamingContent.json func ExampleConfigurationsClient_PutStreamingContent() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() clientFactory, err := testmodule.NewClientFactory("00000000-0000-0000-0000-000000000000", cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } _, err = clientFactory.NewConfigurationsClient().PutStreamingContent(ctx, "2025-01-01", "myResourceGroup", "myConfiguration", streaming.NopCloser(bytes.NewReader([]byte("Configuration file content as a streaming request"))), nil) if err != nil { log.Fatalf("failed to finish the request: %v", err) } } ``` -------------------------------- ### Clean install dependencies Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-java/emitter-tests/readme.md Removes existing node modules and lock files to force a clean environment setup. ```shell rm -rf node_modules rm package-lock.json ``` -------------------------------- ### Usage of Deployment Client Source: https://github.com/azure/typespec-azure/blob/main/packages/typespec-java/docs/developer/2022-09-13-dpg-archboard-review.md Example of calling the deployment client and parsing the BinaryData response. ```java DeploymentsClient deploymentsClient = new DeploymentsClientBuilder() .endpoint("" ) .buildClient(); Response response = deploymentsClient.getDeploymentWithResponse("project-name", "deployment-name", new RequestOptions()); ObjectMapper objectMapper = new ObjectMapper(); BinaryData deployment = response.getValue(); JsonNode jsonNode = objectMapper.readTree(deployment.toBytes()); String projectName = jsonNode.get("projectName").asText(); String description = jsonNode.get("description").asText(); ``` -------------------------------- ### Example Azure DevOps Pipeline with Artifact Publishing Source: https://github.com/azure/typespec-azure/blob/main/website/src/content/docs/docs/howtos/rest-api-publish/buildpipelines.md A more complete Azure DevOps pipeline example that includes setting up NodeJS, installing dependencies, compiling TypeSpec, and publishing the output as a pipeline artifact. Assumes TypeSpec files are at the repository root. ```yaml trigger: - main pool: vmImage: ubuntu-latest steps: - task: NodeTool@0 inputs: versionSpec: "22.x" - script: npm install - script: npx tsp compile . - task: PublishPipelineArtifact@1 displayName: Publish TypeSpec Output Folder inputs: targetPath: "tsp-output" artifact: "tsp-output" publishLocation: "pipeline" ```