Skip to content

speakeasy-api/speakeasy-client-sdk-csharp

Repository files navigation

Speakeasy

Summary

Speakeasy API: The Subscriptions API manages subscriptions for CLI and registry events

For more information about the API: The Speakeasy Platform Documentation

Table of Contents

SDK Installation

NuGet

To add the NuGet package to a .NET project:

dotnet add package SpeakeasySDK

Locally

To add a reference to a local instance of the SDK in a .NET project:

dotnet add reference src/SpeakeasySDK/SpeakeasySDK.csproj

SDK Example Usage

Example

using SpeakeasySDK;
using SpeakeasySDK.Models.Shared;

var sdk = new SDK(security: new Security() {
    APIKey = "<YOUR_API_KEY_HERE>",
});

RemoteSource? req = null;

var res = await sdk.Artifacts.CreateRemoteSourceAsync(req);

// handle response

Available Resources and Operations

Available methods
  • GetAccess - Get access allowances for a particular workspace
  • GetAccessToken - Get or refresh an access token for the current workspace.
  • GetUser - Get information about the current user.
  • ValidateApiKey - Validate the current api key.
  • GetEventsByTarget - Load recent events for a particular workspace
  • GetTargets - Load targets for a particular workspace
  • GetTargetsDeprecated - Load targets for a particular workspace
  • Post - Post events for a specific workspace
  • Search - Search events for a particular workspace by any field
  • Create - Create a publishing token for a workspace
  • Delete - Delete a specific publishing token
  • Get - Get a specific publishing token
  • List - Get publishing tokens for a workspace
  • ResolveMetadata - Get metadata about the token
  • ResolveTarget - Get a specific publishing token target
  • Update - Updates the validitity period of a publishing token
  • Suggest - Generate suggestions for improving an OpenAPI document.
  • SuggestItems - Generate generic suggestions for a list of items.
  • SuggestOpenAPI - (DEPRECATED) Generate suggestions for improving an OpenAPI document.
  • SuggestOpenAPIRegistry - Generate suggestions for improving an OpenAPI document stored in the registry.

Server Selection

Select Server by Name

You can override the default server globally by passing a server name to the server: string optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:

Name Server Description
prod https://api.prod.speakeasy.com

Example

using SpeakeasySDK;
using SpeakeasySDK.Models.Shared;

var sdk = new SDK(
    server: SDKConfig.Server.Prod,
    security: new Security() {
        APIKey = "<YOUR_API_KEY_HERE>",
    }
);

RemoteSource? req = null;

var res = await sdk.Artifacts.CreateRemoteSourceAsync(req);

// handle response

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:

using SpeakeasySDK;
using SpeakeasySDK.Models.Shared;

var sdk = new SDK(
    serverUrl: "https://api.prod.speakeasy.com",
    security: new Security() {
        APIKey = "<YOUR_API_KEY_HERE>",
    }
);

RemoteSource? req = null;

var res = await sdk.Artifacts.CreateRemoteSourceAsync(req);

// handle response

Authentication

Per-Client Security Schemes

This SDK supports the following security schemes globally:

Name Type Scheme
APIKey apiKey API key
Bearer http HTTP Bearer
WorkspaceIdentifier apiKey API key

You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:

using SpeakeasySDK;
using SpeakeasySDK.Models.Shared;

var sdk = new SDK(security: new Security() {
    APIKey = "<YOUR_API_KEY_HERE>",
});

RemoteSource? req = null;

var res = await sdk.Artifacts.CreateRemoteSourceAsync(req);

// handle response

Global Parameters

A parameter is configured globally. This parameter may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, This global value will be used as the default on the operations that use it. When such operations are called, there is a place in each to override the global value, if needed.

For example, you can set workspace_id to "<id>" at SDK initialization and then you do not have to pass the same value on calls to operations like GetAccessToken. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.

Available Globals

The following global parameter is available.

Name Type Description
workspaceId string The WorkspaceId parameter.

Example

using SpeakeasySDK;
using SpeakeasySDK.Models.Operations;

var sdk = new SDK(workspaceId: "<id>");

GetAccessTokenRequest req = new GetAccessTokenRequest() {
    WorkspaceId = "<id>",
};

var res = await sdk.Auth.GetAccessTokenAsync(req);

// handle response

Error Handling

SDKBaseException is the base exception class for all HTTP error responses. It has the following properties:

Property Type Description
Message string Error message
StatusCode int HTTP status code
Headers HttpResponseHeaders HTTP headers
ContentType string? HTTP content type
RawResponse HttpResponseMessage HTTP response object
Body string HTTP response body

Some exceptions in this SDK include an additional Payload field, which will contain deserialized custom error data when present. Possible exceptions are listed in the Error Classes section.

Example

using SpeakeasySDK;
using SpeakeasySDK.Models.Errors;
using SpeakeasySDK.Models.Shared;

var sdk = new SDK(security: new Security() {
    APIKey = "<YOUR_API_KEY_HERE>",
});

try
{
    RemoteSource? req = null;

    var res = await sdk.Artifacts.CreateRemoteSourceAsync(req);

    // handle response
}
catch (SDKBaseException ex)  // all SDK exceptions inherit from SDKBaseException
{
    // ex.ToString() provides a detailed error message
    System.Console.WriteLine(ex);

    // Base exception fields
    HttpResponseMessage rawResponse = ex.RawResponse;
    HttpResponseHeaders headers = ex.Headers;
    int statusCode = ex.StatusCode;
    string? contentType = ex.ContentType;
    var responseBody = ex.Body;

    if (ex is Error) // different exceptions may be thrown depending on the method
    {
        // Check error data fields
        ErrorPayload payload = ex.Payload;
        string Message = payload.Message;
        int StatusCode = payload.StatusCode;
    }

    // An underlying cause may be provided
    if (ex.InnerException != null)
    {
        Exception cause = ex.InnerException;
    }
}
catch (System.Net.Http.HttpRequestException ex)
{
    // Check ex.InnerException for Network connectivity errors
}

Error Classes

Primary exceptions:

  • SDKBaseException: The base class for HTTP error responses.
    • Error: The Status type defines a logical error model. *
Less common exceptions (2)

* Refer to the relevant documentation to determine whether an exception applies to a specific operation.

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply pass a RetryConfig to the call:

using SpeakeasySDK;
using SpeakeasySDK.Models.Operations;
using SpeakeasySDK.Models.Shared;

var sdk = new SDK(security: new Security() {
    APIKey = "<YOUR_API_KEY_HERE>",
});

GetWorkspaceAccessRequest? req = null;

var res = await sdk.Auth.GetAccessAsync(
    retryConfig: new RetryConfig(
        strategy: RetryConfig.RetryStrategy.BACKOFF,
        backoff: new BackoffStrategy(
            initialIntervalMs: 1L,
            maxIntervalMs: 50L,
            maxElapsedTimeMs: 100L,
            exponent: 1.1
        ),
        retryConnectionErrors: false
    ),
    request: req
);

// handle response

If you'd like to override the default retry strategy for all operations that support retries, you can use the RetryConfig optional parameter when intitializing the SDK:

using SpeakeasySDK;
using SpeakeasySDK.Models.Operations;
using SpeakeasySDK.Models.Shared;

var sdk = new SDK(
    retryConfig: new RetryConfig(
        strategy: RetryConfig.RetryStrategy.BACKOFF,
        backoff: new BackoffStrategy(
            initialIntervalMs: 1L,
            maxIntervalMs: 50L,
            maxElapsedTimeMs: 100L,
            exponent: 1.1
        ),
        retryConnectionErrors: false
    ),
    security: new Security() {
        APIKey = "<YOUR_API_KEY_HERE>",
    }
);

GetWorkspaceAccessRequest? req = null;

var res = await sdk.Auth.GetAccessAsync(req);

// handle response

Custom HTTP Client

The C# SDK makes API calls using an ISpeakeasyHttpClient that wraps the native HttpClient. This client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The ISpeakeasyHttpClient interface allows you to either use the default SpeakeasyHttpClient that comes with the SDK, or provide your own custom implementation with customized configuration such as custom message handlers, timeouts, connection pooling, and other HTTP client settings.

The following example shows how to create a custom HTTP client with request modification and error handling:

using SpeakeasySDK;
using SpeakeasySDK.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

// Create a custom HTTP client
public class CustomHttpClient : ISpeakeasyHttpClient
{
    private readonly ISpeakeasyHttpClient _defaultClient;

    public CustomHttpClient()
    {
        _defaultClient = new SpeakeasyHttpClient();
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        // Add custom header and timeout
        request.Headers.Add("x-custom-header", "custom value");
        request.Headers.Add("x-request-timeout", "30");
        
        try
        {
            var response = await _defaultClient.SendAsync(request, cancellationToken);
            // Log successful response
            Console.WriteLine($"Request successful: {response.StatusCode}");
            return response;
        }
        catch (Exception error)
        {
            // Log error
            Console.WriteLine($"Request failed: {error.Message}");
            throw;
        }
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
        _defaultClient?.Dispose();
    }
}

// Use the custom HTTP client with the SDK
var customHttpClient = new CustomHttpClient();
var sdk = new SDK(client: customHttpClient);
You can also provide a completely custom HTTP client with your own configuration:
using SpeakeasySDK.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

// Custom HTTP client with custom configuration
public class AdvancedHttpClient : ISpeakeasyHttpClient
{
    private readonly HttpClient _httpClient;

    public AdvancedHttpClient()
    {
        var handler = new HttpClientHandler()
        {
            MaxConnectionsPerServer = 10,
            // ServerCertificateCustomValidationCallback = customCertValidation, // Custom SSL validation if needed
        };

        _httpClient = new HttpClient(handler)
        {
            Timeout = TimeSpan.FromSeconds(30)
        };
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        return await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None);
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}

var sdk = SDK.Builder()
    .WithClient(new AdvancedHttpClient())
    .Build();
For simple debugging, you can enable request/response logging by implementing a custom client:
public class LoggingHttpClient : ISpeakeasyHttpClient
{
    private readonly ISpeakeasyHttpClient _innerClient;

    public LoggingHttpClient(ISpeakeasyHttpClient innerClient = null)
    {
        _innerClient = innerClient ?? new SpeakeasyHttpClient();
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        // Log request
        Console.WriteLine($"Sending {request.Method} request to {request.RequestUri}");
        
        var response = await _innerClient.SendAsync(request, cancellationToken);
        
        // Log response
        Console.WriteLine($"Received {response.StatusCode} response");
        
        return response;
    }

    public void Dispose() => _innerClient?.Dispose();
}

var sdk = new SDK(client: new LoggingHttpClient());

The SDK also provides built-in hook support through the SDKConfiguration.Hooks system, which automatically handles BeforeRequestAsync, AfterSuccessAsync, and AfterErrorAsync hooks for advanced request lifecycle management.

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!

SDK Created by Speakeasy

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages