or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdindex.mdoperations.mdpipeline.mdpolicies.mdserialization.mdservice-client.md
tile.json

service-client.mddocs/

Service Client

The ServiceClient class provides the core HTTP client functionality for Azure SDK client libraries. It serves as the base class that handles request/response lifecycle management with operation specifications and HTTP pipeline integration.

Capabilities

ServiceClient Class

The main client class that all generated Azure SDK clients extend. Provides two primary methods for making HTTP requests: sendRequest for raw HTTP calls and sendOperationRequest for operation-specification-based calls.

/**
 * Base class for Azure service clients providing HTTP request/response handling
 */
class ServiceClient {
  /**
   * Creates a new ServiceClient instance
   * @param options - Configuration options for the client
   */
  constructor(options?: ServiceClientOptions);

  /**
   * Send a raw HTTP request through the pipeline
   * @param request - The HTTP request to send
   * @returns Promise resolving to the HTTP response
   */
  sendRequest(request: PipelineRequest): Promise<PipelineResponse>;

  /**
   * Send an operation request based on OpenAPI specification
   * @param operationArguments - Arguments for the operation
   * @param operationSpec - Specification defining the operation
   * @returns Promise resolving to the parsed response data
   */
  sendOperationRequest<T>(
    operationArguments: OperationArguments,
    operationSpec: OperationSpec
  ): Promise<T>;

  /** The HTTP pipeline used by this client for processing requests */
  readonly pipeline: Pipeline;
}

Service Client Options

Configuration interface for initializing ServiceClient instances with endpoint, authentication, and pipeline settings.

/**
 * Configuration options for ServiceClient initialization
 */
interface ServiceClientOptions extends CommonClientOptions {
  /**
   * Base URI for requests (deprecated - use endpoint instead)
   * @deprecated Use endpoint property instead
   */
  baseUri?: string;

  /**
   * Endpoint URL for the service
   */
  endpoint?: string;

  /**
   * OAuth scopes for bearer token authentication
   */
  credentialScopes?: string | string[];

  /**
   * Default content type for requests
   */
  requestContentType?: string;

  /**
   * Authentication credential from @azure/core-auth
   */
  credential?: TokenCredential;

  /**
   * Custom HTTP pipeline to use instead of creating default
   */
  pipeline?: Pipeline;
}

Usage Examples

Creating a Basic Service Client

import { ServiceClient } from "@azure/core-client";

// Create a simple service client
const client = new ServiceClient({
  endpoint: "https://myservice.azure.com",
  requestContentType: "application/json"
});

// Make a raw HTTP request
const response = await client.sendRequest({
  url: "https://myservice.azure.com/api/data",
  method: "GET"
});

Service Client with Authentication

import { ServiceClient, createClientPipeline } from "@azure/core-client";
import { DefaultAzureCredential } from "@azure/identity";

// Create client with authentication
const credential = new DefaultAzureCredential();
const pipeline = createClientPipeline({
  credentialOptions: {
    credential,
    credentialScopes: ["https://management.azure.com/.default"]
  }
});

const client = new ServiceClient({
  endpoint: "https://management.azure.com",
  pipeline
});

Extending ServiceClient

import { ServiceClient, createSerializer } from "@azure/core-client";
import type { OperationSpec, OperationArguments } from "@azure/core-client";

class MyAzureServiceClient extends ServiceClient {
  constructor(endpoint: string, options?: ServiceClientOptions) {
    super({
      endpoint,
      ...options
    });
  }

  async getResource(resourceId: string): Promise<Resource> {
    const operationSpec: OperationSpec = {
      httpMethod: "GET",
      path: "/resources/{resourceId}",
      serializer: createSerializer(),
      urlParameters: [{
        parameterPath: "resourceId",
        mapper: {
          serializedName: "resourceId",
          type: { name: "String" }
        }
      }],
      responses: {
        200: {
          bodyMapper: {
            type: { name: "Composite" },
            serializedName: "Resource"
          }
        }
      }
    };

    return this.sendOperationRequest({ resourceId }, operationSpec);
  }
}

Custom Pipeline Configuration

import { ServiceClient, createClientPipeline } from "@azure/core-client";
import { logPolicy } from "@azure/core-rest-pipeline";

// Create client with custom pipeline policies
const pipeline = createClientPipeline({
  serializationOptions: {
    stringifyXML: customXMLStringifier
  }
});

// Add custom logging policy
pipeline.addPolicy(logPolicy({ 
  logger: myCustomLogger,
  allowedHeaderNames: ["x-ms-request-id"]
}));

const client = new ServiceClient({
  endpoint: "https://myservice.azure.com",
  pipeline
});

Integration with Core Types

The ServiceClient works seamlessly with other @azure/core-client types:

  • Pipeline: Uses HTTP pipeline for request processing
  • OperationSpec: Defines operation structure and serialization
  • OperationArguments: Contains parameter values for operations
  • Serializer: Handles data transformation between objects and HTTP payloads
  • CommonClientOptions: Extends base options with additional HTTP client configuration

Error Handling

ServiceClient automatically handles HTTP errors and includes detailed error information:

try {
  const result = await client.sendOperationRequest(args, spec);
} catch (error) {
  if (error.statusCode === 404) {
    console.log("Resource not found");
  } else if (error.statusCode >= 500) {
    console.log("Server error:", error.message);
  }
  // Error includes full response details
  console.log("Response body:", error.response?.parsedBody);
}