Custom Code With SDK Hooks
Availability
SDK Hooks are available for 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:
Language | Directory Path |
---|---|
Go | internal/hooks |
Python | src/{sdk_name}/hooks |
Python (v2) | src/{sdk_name}/_hooks |
TypeScript | src/hooks |
Java | src/main/java/{package_path}/hooks |
C# | {root_path}/Hooks |
Steps to Add a Hook
- 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.
- Locate the registration file.
Find the appropriate registration file for the language:
Language | Registration File Path |
---|---|
Go | internal/hooks/registration.go |
Python | src/{sdk_name}/hooks/registration.py |
Python(v2) | src/{sdk_name}/_hooks/registration.py |
TypeScript | src/hooks/registration.ts |
Java | src/main/java/{package_path}/hooks/SDKHooks.java |
C# | {root_path}/Hooks/HookRegistration.cs |
- Instantiate and register your 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.
package hooksfunc initHooks(h *Hooks) { myHook := &ExampleHook{} h.registerBeforeRequestHook(myHook)}
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:
package hooksimport ( "net/http")type ExampleHook struct{}var ( _ sdkInitHook = (*ExampleHook)(nil) _ beforeRequestHook = (*ExampleHook)(nil) _ afterSuccessHook = (*ExampleHook)(nil) _ afterErrorHook = (*ExampleHook)(nil))func (i *ExampleHook) SDKInit(baseURL string, client HTTPClient) (string, HTTPClient) { // modify the baseURL or wrap the client used by the SDK here and return the updated values return baseURL, client}func (i *ExampleHook) BeforeRequest(hookCtx BeforeRequestContext, req *http.Request) (*http.Request, error) { // modify the request object before it is sent, such as adding headers or query parameters, or return an error to stop the request from being sent return req, nil}func (i *ExampleHook) AfterSuccess(hookCtx AfterSuccessContext, res *http.Response) (*http.Response, error) { // modify the response object before deserialization or return an error to stop the response from being deserialized return res, nil}func (i *ExampleHook) AfterError(hookCtx AfterErrorContext, res *http.Response, err error) (*http.Response, error) { // modify the response before it is deserialized as a custom error or the error object before it is returned or return an error wrapped in the FailEarly error in this package to exit from the hook chain early return res, err}
Adding Dependencies
To add dependencies needed for SDK hooks, configure the additionalDependencies
section in the gen.yaml
file.
configVersion: 2.0.0go:additionalDependencies: # Pass a map of Go package names to the version to be added to the `go.mod` file of the SDK. "github.com/google/uuid": v1.6.0