Skip to Content
DocumentationCustomizeAdd Custom CodeCustom code with SDK hooks

Custom Code With SDK Hooks

ℹ️
Availability

SDK Hooks are available for Business and Enterprise users only.

SDK Hooks enable custom logic to be added to SDK functions and request lifecycles across supported SDKs. These hooks allow for transformations, tracing, logging, validation, and error handling during different stages of the SDK’s lifecycle.

Hooks can be applied to the following lifecycle events:

  • On SDK initialization: Modify the base server URL, wrap or override the HTTP client, add tracing, inject global headers, and manage authentication.
  • Before request: Cancel an outgoing request, transform the request contents, or add tracing.
  • After success: When a successful response is received, add tracing and logging, validate the response, return an error, or transform the raw response before deserialization.
  • After error: On connection errors or unsuccessful responses, add tracing and logging or transform the returned error.

Add a Hook

Hooks are supported in SDKs generated with the latest Speakeasy CLI. Each supported language includes a hooks directory in the generated code:

LanguageDirectory Path
Go
Python
TypeScript
Java
C#
Ruby

Steps to Add a Hook

  1. Create a hook implementation.

Add the custom hook implementation in a new file inside the hooks directory. The generator won’t override files added to this directory.

  1. Locate the registration file.

Find the appropriate registration file for the language:

LanguageRegistration File Path
Go
Python
TypeScript
Java
C#
Ruby
  1. Instantiate and register the hook.

In the registration file, find the method initHooks/init_hooks/initialize/InitHooks. This method includes a hooks parameter, allowing hooks to be registered for various lifecycle events.

Instantiate the hook here and register it for the appropriate event.

ℹ️
Note

The registration file is generated once and will not be overwritten. After the initial generation, you have full control and ownership of it.

Here are example hook implementations for each of the lifecycle events across different languages:

Adding Dependencies

To add dependencies needed for SDK hooks, configure the additionalDependencies section in the gen.yaml file.

Last updated on