Class ApiBase
- Namespace
- GenerativeAI.Core
- Assembly
- GenerativeAI.dll
Base class for handling API requests and responses.
public abstract class ApiBase
- Inheritance
-
ApiBase
- Derived
- Inherited Members
- Extension Methods
Constructors
ApiBase(HttpClient?, ILogger?)
Initializes a new instance of the ApiBase class.
protected ApiBase(HttpClient? httpClient, ILogger? logger = null)
Parameters
httpClientHttpClientHTTP client used for API requests.
loggerILoggerOptional. The logger instance for logging API interactions.
Properties
HttpClient
Provides an HTTP client for sending and receiving HTTP requests and responses. This property is used to facilitate communication with APIs or services.
protected HttpClient HttpClient { get; }
Property Value
Logger
Gets the logger instance for diagnostic and error logging.
protected ILogger? Logger { get; }
Property Value
SerializerOptions
JSON serialization options used for API requests and responses.
protected JsonSerializerOptions? SerializerOptions { get; }
Property Value
Methods
AddAuthorizationHeader(HttpRequestMessage, bool, CancellationToken)
Adds authorization headers to an HTTP request.
protected virtual Task AddAuthorizationHeader(HttpRequestMessage request, bool requireAccessToken = false, CancellationToken cancellationToken = default)
Parameters
requestHttpRequestMessageThe HTTP request where headers will be added.
requireAccessTokenboolWhether an access token is required for the request.
cancellationTokenCancellationTokenToken to monitor for cancellation requests.
Returns
Remarks
Override this method in derived classes to dynamically add authorization headers. By default, this implementation does nothing.
CheckAndHandleErrors(HttpResponseMessage, string)
Checks if the HTTP response indicates a successful status, and throws an exception with detailed error information otherwise.
protected Task CheckAndHandleErrors(HttpResponseMessage response, string url)
Parameters
responseHttpResponseMessageThe HTTP response to evaluate.
urlstringThe URL associated with the HTTP request, used for logging or exception messages.
Returns
Exceptions
- ApiException
Thrown when the API returns an error with a valid "error" object containing status, code, or message details.
- HttpRequestException
Thrown when the HTTP response indicates a failure, but no detailed "error" object is present in the response body.
DeleteAsync(string, CancellationToken)
Sends a DELETE request to the specified URL.
protected Task<bool> DeleteAsync(string url, CancellationToken cancellationToken = default)
Parameters
urlstringThe full URL of the API endpoint.
cancellationTokenCancellationTokenToken to propagate notification that the operation should be canceled.
Returns
Exceptions
- HttpRequestException
Throws upon a non-success status code.
Deserialize<T>(HttpResponseMessage)
Deserializes a JSON string into an object of the specified type.
protected Task<T?> Deserialize<T>(HttpResponseMessage response)
Parameters
responseHttpResponseMessageThe response to deserialize.
Returns
- Task<T>
The deserialized object of type T, or null if deserialization fails.
Type Parameters
TThe type of object to deserialize into.
Deserialize<T>(string)
Deserializes a JSON string into an object of the specified type.
protected T? Deserialize<T>(string json)
Parameters
jsonstringThe JSON string to deserialize.
Returns
- T
The deserialized object of type T, or null if deserialization fails.
Type Parameters
TThe type of object to deserialize into.
GetAsync<T>(string, CancellationToken)
Sends a GET request to the specified URL.
protected Task<T> GetAsync<T>(string url, CancellationToken cancellationToken = default)
Parameters
urlstringThe full URL of the API endpoint.
cancellationTokenCancellationTokenToken to propagate notification that the operation should be canceled.
Returns
- Task<T>
The deserialized object from the response.
Type Parameters
TThe type to deserialize the response into.
Exceptions
- HttpRequestException
Throws upon a non-success status code.
- InvalidOperationException
Throws if deserialization fails.
SendAsync<TRequest, TResponse>(string, TRequest, HttpMethod, CancellationToken)
Sends an HTTP request (e.g., POST, PUT, or PATCH) to the specified URL.
protected Task<TResponse> SendAsync<TRequest, TResponse>(string url, TRequest payload, HttpMethod method, CancellationToken cancellationToken = default)
Parameters
urlstringThe full URL of the API endpoint.
payloadTRequestThe request payload to send in the body.
methodHttpMethodThe HTTP method (e.g., POST, PUT, PATCH).
cancellationTokenCancellationTokenToken to propagate notification that the operation should be canceled.
Returns
- Task<TResponse>
The deserialized object from the response.
Type Parameters
TRequestThe type of the request payload.
TResponseThe type to deserialize the response into.
Exceptions
- HttpRequestException
Throws upon a non-success status code.
- InvalidOperationException
Throws if deserialization fails.
StreamAsync<TRequest, TResponse>(string, TRequest, CancellationToken)
Streams responses by sending an HTTP request with a JSON payload and yielding the deserialized items as they arrive.
protected IAsyncEnumerable<TResponse> StreamAsync<TRequest, TResponse>(string url, TRequest payload, CancellationToken cancellationToken = default)
Parameters
urlstringThe target endpoint URL to which the request is sent.
payloadTRequestThe request payload.
cancellationTokenCancellationTokenA token for cancelling the operation.
Returns
- IAsyncEnumerable<TResponse>
An async stream of response items.
Type Parameters
TRequestThe type of the request payload to serialize.
TResponseThe type of the response items to deserialize.
UploadFileWithProgressAsync(Stream, string, string, string, Action<double>, Dictionary<string, string>?, CancellationToken)
Uploads a file asynchronously to the specified URL with progress tracking.
protected Task<string> UploadFileWithProgressAsync(Stream stream, string filePath, string mimeType, string url, Action<double> progress, Dictionary<string, string>? additionalHeaders = null, CancellationToken cancellationToken = default)
Parameters
streamStreamThe stream containing the file data to upload.
filePathstringThe full path to the file to upload.
mimeTypestringThe MIME type of the file being uploaded.
urlstringThe destination URL to upload the file.
progressAction<double>An action to report progress as a percentage between 0 and 100.
additionalHeadersDictionary<string, string>Optional. A dictionary of additional headers to include with the upload request.
cancellationTokenCancellationTokenOptional. A token to cancel the file upload operation.
Returns
- Task<string>
A task that represents the asynchronous upload operation. The task result contains the response string from the server.
UploadFileWithProgressAsync(string, string, Action<double>, Dictionary<string, string>?, CancellationToken)
Uploads a file to the specified URL with progress reporting.
protected Task<string> UploadFileWithProgressAsync(string url, string filePath, Action<double> progress, Dictionary<string, string>? additionalHeaders = null, CancellationToken cancellationToken = default)
Parameters
urlstringThe full URL of the API endpoint.
filePathstringThe local path to the file to be uploaded.
progressAction<double>A callback function to report upload progress as a percentage.
additionalHeadersDictionary<string, string>Optional. Additional headers to add to the request.
cancellationTokenCancellationTokenToken to propagate notification that the operation should be canceled.