browserbaseunofficial

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 1, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

Browserbase Unofficial Go API Library

Go Reference

The Browserbase Unofficial Go library provides convenient access to the Browserbase Unofficial REST API from applications written in Go.

It is generated with Stainless.

Installation

import (
	"github.com/RobinLbt/browserbase-unofficial-go" // imported as browserbaseunofficial
)

Or to pin the version:

go get -u 'github.com/RobinLbt/[email protected]'

Requirements

This library requires Go 1.22+.

Usage

The full API of this library can be found in api.md.

package main

import (
	"context"
	"fmt"

	"github.com/RobinLbt/browserbase-unofficial-go"
	"github.com/RobinLbt/browserbase-unofficial-go/option"
)

func main() {
	client := browserbaseunofficial.NewClient(
		option.WithAPIKey("My API Key"), // defaults to os.LookupEnv("BROWSERBASE_UNOFFICIAL_API_KEY")
	)
	createContextResponse, err := client.Contexts.New(context.TODO(), browserbaseunofficial.ContextNewParams{
		ProjectID: "projectId",
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", createContextResponse.ID)
}

Request fields

The browserbaseunofficial library uses the omitzero semantics from the Go 1.24+ encoding/json release for request fields.

Required primitive fields (int64, string, etc.) feature the tag `json:"...,required"`. These fields are always serialized, even their zero values.

Optional primitive types are wrapped in a param.Opt[T]. These fields can be set with the provided constructors, browserbaseunofficial.String(string), browserbaseunofficial.Int(int64), etc.

Any param.Opt[T], map, slice, struct or string enum uses the tag `json:"...,omitzero"`. Its zero value is considered omitted.

The param.IsOmitted(any) function can confirm the presence of any omitzero field.

p := browserbaseunofficial.ExampleParams{
	ID:   "id_xxx",                            // required property
	Name: browserbaseunofficial.String("..."), // optional property

	Point: browserbaseunofficial.Point{
		X: 0,                            // required field will serialize as 0
		Y: browserbaseunofficial.Int(1), // optional field will serialize as 1
		// ... omitted non-required fields will not be serialized
	},

	Origin: browserbaseunofficial.Origin{}, // the zero value of [Origin] is considered omitted
}

To send null instead of a param.Opt[T], use param.Null[T](). To send null instead of a struct T, use param.NullStruct[T]().

p.Name = param.Null[string]()       // 'null' instead of string
p.Point = param.NullStruct[Point]() // 'null' instead of struct

param.IsNull(p.Name)  // true
param.IsNull(p.Point) // true

Request structs contain a .SetExtraFields(map[string]any) method which can send non-conforming fields in the request body. Extra fields overwrite any struct fields with a matching key. For security reasons, only use SetExtraFields with trusted data.

To send a custom value instead of a struct, use param.Override[T](value).

// In cases where the API specifies a given type,
// but you want to send something else, use [SetExtraFields]:
p.SetExtraFields(map[string]any{
	"x": 0.01, // send "x" as a float instead of int
})

// Send a number instead of an object
custom := param.Override[browserbaseunofficial.FooParams](12)
Request unions

Unions are represented as a struct with fields prefixed by "Of" for each of its variants, only one field can be non-zero. The non-zero field will be serialized.

Sub-properties of the union can be accessed via methods on the union struct. These methods return a mutable pointer to the underlying data, if present.

// Only one field can be non-zero, use param.IsOmitted() to check if a field is set
type AnimalUnionParam struct {
	OfCat *Cat `json:",omitzero,inline`
	OfDog *Dog `json:",omitzero,inline`
}

animal := AnimalUnionParam{
	OfCat: &Cat{
		Name: "Whiskers",
		Owner: PersonParam{
			Address: AddressParam{Street: "3333 Coyote Hill Rd", Zip: 0},
		},
	},
}

// Mutating a field
if address := animal.GetOwner().GetAddress(); address != nil {
	address.ZipCode = 94304
}
Response objects

All fields in response structs are ordinary value types (not pointers or wrappers). Response structs also include a special JSON field containing metadata about each property.

type Animal struct {
	Name   string `json:"name,nullable"`
	Owners int    `json:"owners"`
	Age    int    `json:"age"`
	JSON   struct {
		Name        respjson.Field
		Owner       respjson.Field
		Age         respjson.Field
		ExtraFields map[string]respjson.Field
	} `json:"-"`
}

To handle optional data, use the .Valid() method on the JSON field. .Valid() returns true if a field is not null, not present, or couldn't be marshaled.

If .Valid() is false, the corresponding field will simply be its zero value.

raw := `{"owners": 1, "name": null}`

var res Animal
json.Unmarshal([]byte(raw), &res)

// Accessing regular fields

res.Owners // 1
res.Name   // ""
res.Age    // 0

// Optional field checks

res.JSON.Owners.Valid() // true
res.JSON.Name.Valid()   // false
res.JSON.Age.Valid()    // false

// Raw JSON values

res.JSON.Owners.Raw()                  // "1"
res.JSON.Name.Raw() == "null"          // true
res.JSON.Name.Raw() == respjson.Null   // true
res.JSON.Age.Raw() == ""               // true
res.JSON.Age.Raw() == respjson.Omitted // true

These .JSON structs also include an ExtraFields map containing any properties in the json response that were not specified in the struct. This can be useful for API features not yet present in the SDK.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
Response Unions

In responses, unions are represented by a flattened struct containing all possible fields from each of the object variants. To convert it to a variant use the .AsFooVariant() method or the .AsAny() method if present.

If a response value union contains primitive values, primitive fields will be alongside the properties but prefixed with Of and feature the tag json:"...,inline".

type AnimalUnion struct {
	// From variants [Dog], [Cat]
	Owner Person `json:"owner"`
	// From variant [Dog]
	DogBreed string `json:"dog_breed"`
	// From variant [Cat]
	CatBreed string `json:"cat_breed"`
	// ...

	JSON struct {
		Owner respjson.Field
		// ...
	} `json:"-"`
}

// If animal variant
if animal.Owner.Address.ZipCode == "" {
	panic("missing zip code")
}

// Switch on the variant
switch variant := animal.AsAny().(type) {
case Dog:
case Cat:
default:
	panic("unexpected type")
}
RequestOptions

This library uses the functional options pattern. Functions defined in the option package return a RequestOption, which is a closure that mutates a RequestConfig. These options can be supplied to the client or at individual requests. For example:

client := browserbaseunofficial.NewClient(
	// Adds a header to every request made by the client
	option.WithHeader("X-Some-Header", "custom_header_info"),
)

client.Contexts.New(context.TODO(), ...,
	// Override the header
	option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
	// Add an undocumented field to the request body, using sjson syntax
	option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
)

The request option option.WithDebugLog(nil) may be helpful while debugging.

See the full list of request options.

Pagination

This library provides some conveniences for working with paginated list endpoints.

You can use .ListAutoPaging() methods to iterate through items across all pages:

Or you can use simple .List() methods to fetch a single page and receive a standard response object with additional helper methods like .GetNextPage(), e.g.:

Errors

When the API returns a non-success status code, we return an error with type *browserbaseunofficial.Error. This contains the StatusCode, *http.Request, and *http.Response values of the request, as well as the JSON of the error body (much like other response objects in the SDK).

To handle errors, we recommend that you use the errors.As pattern:

_, err := client.Contexts.New(context.TODO(), browserbaseunofficial.ContextNewParams{
	ProjectID: "projectId",
})
if err != nil {
	var apierr *browserbaseunofficial.Error
	if errors.As(err, &apierr) {
		println(string(apierr.DumpRequest(true)))  // Prints the serialized HTTP request
		println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
	}
	panic(err.Error()) // GET "/v1/contexts": 400 Bad Request { ... }
}

When other errors occur, they are returned unwrapped; for example, if HTTP transport fails, you might receive *url.Error wrapping *net.OpError.

Timeouts

Requests do not time out by default; use context to configure a timeout for a request lifecycle.

Note that if a request is retried, the context timeout does not start over. To set a per-retry timeout, use option.WithRequestTimeout().

// This sets the timeout for the request, including all the retries.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client.Contexts.New(
	ctx,
	browserbaseunofficial.ContextNewParams{
		ProjectID: "projectId",
	},
	// This sets the per-retry timeout
	option.WithRequestTimeout(20*time.Second),
)
File uploads

Request parameters that correspond to file uploads in multipart requests are typed as io.Reader. The contents of the io.Reader will by default be sent as a multipart form part with the file name of "anonymous_file" and content-type of "application/octet-stream".

The file name and content-type can be customized by implementing Name() string or ContentType() string on the run-time type of io.Reader. Note that os.File implements Name() string, so a file returned by os.Open will be sent with the file name on disk.

We also provide a helper browserbaseunofficial.File(reader io.Reader, filename string, contentType string) which can be used to wrap any io.Reader with the appropriate file name and content type.

// A file from the file system
file, err := os.Open("/path/to/file")
browserbaseunofficial.ExtensionNewParams{
	File: file,
}

// A file from a string
browserbaseunofficial.ExtensionNewParams{
	File: strings.NewReader("my file contents"),
}

// With a custom filename and contentType
browserbaseunofficial.ExtensionNewParams{
	File: browserbaseunofficial.File(strings.NewReader(`{"hello": "foo"}`), "file.go", "application/json"),
}
Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff. We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors.

You can use the WithMaxRetries option to configure or disable this:

// Configure the default for all requests:
client := browserbaseunofficial.NewClient(
	option.WithMaxRetries(0), // default is 2
)

// Override per-request:
client.Contexts.New(
	context.TODO(),
	browserbaseunofficial.ContextNewParams{
		ProjectID: "projectId",
	},
	option.WithMaxRetries(5),
)
Accessing raw response data (e.g. response headers)

You can access the raw HTTP response data by using the option.WithResponseInto() request option. This is useful when you need to examine response headers, status codes, or other details.

// Create a variable to store the HTTP response
var response *http.Response
createContextResponse, err := client.Contexts.New(
	context.TODO(),
	browserbaseunofficial.ContextNewParams{
		ProjectID: "projectId",
	},
	option.WithResponseInto(&response),
)
if err != nil {
	// handle error
}
fmt.Printf("%+v\n", createContextResponse)

fmt.Printf("Status Code: %d\n", response.StatusCode)
fmt.Printf("Headers: %+#v\n", response.Header)
Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can use client.Get, client.Post, and other HTTP verbs. RequestOptions on the client, such as retries, will be respected when making these requests.

var (
    // params can be an io.Reader, a []byte, an encoding/json serializable object,
    // or a "…Params" struct defined in this library.
    params map[string]any

    // result can be an []byte, *http.Response, a encoding/json deserializable object,
    // or a model defined in this library.
    result *http.Response
)
err := client.Post(context.Background(), "/unspecified", params, &result)
if err != nil {
    …
}
Undocumented request params

To make requests using undocumented parameters, you may use either the option.WithQuerySet() or the option.WithJSONSet() methods.

params := FooNewParams{
    ID:   "id_xxxx",
    Data: FooNewParamsData{
        FirstName: browserbaseunofficial.String("John"),
    },
}
client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))
Undocumented response properties

To access undocumented response properties, you may either access the raw JSON of the response as a string with result.JSON.RawJSON(), or get the raw JSON of a particular field on the result with result.JSON.Foo.Raw().

Any fields that are not present on the response struct will be saved and can be accessed by result.JSON.ExtraFields() which returns the extra fields as a map[string]Field.

Middleware

We provide option.WithMiddleware which applies the given middleware to requests.

func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) {
	// Before the request
	start := time.Now()
	LogReq(req)

	// Forward the request to the next handler
	res, err = next(req)

	// Handle stuff after the request
	end := time.Now()
	LogRes(res, err, start - end)

    return res, err
}

client := browserbaseunofficial.NewClient(
	option.WithMiddleware(Logger),
)

When multiple middlewares are provided as variadic arguments, the middlewares are applied left to right. If option.WithMiddleware is given multiple times, for example first in the client then the method, the middleware in the client will run first and the middleware given in the method will run next.

You may also replace the default http.Client with option.WithHTTPClient(client). Only one http client is accepted (this overwrites any previous client) and receives requests after any middleware has been applied.

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Contributing

See the contributing documentation.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) param.Opt[bool]

func BoolPtr

func BoolPtr(v bool) *bool

func DefaultClientOptions

func DefaultClientOptions() []option.RequestOption

DefaultClientOptions read from the environment (BROWSERBASE_UNOFFICIAL_API_KEY, BROWSERBASE_UNOFFICIAL_BASE_URL). This should be used to initialize new clients.

func File

func File(rdr io.Reader, filename string, contentType string) file

func Float

func Float(f float64) param.Opt[float64]

func FloatPtr

func FloatPtr(v float64) *float64

func Int

func Int(i int64) param.Opt[int64]

func IntPtr

func IntPtr(v int64) *int64

func Opt

func Opt[T comparable](v T) param.Opt[T]

func Ptr

func Ptr[T any](v T) *T

func String

func String(s string) param.Opt[string]

func StringPtr

func StringPtr(v string) *string

func Time

func Time(t time.Time) param.Opt[time.Time]

func TimePtr

func TimePtr(v time.Time) *time.Time

Types

type Client

type Client struct {
	Options    []option.RequestOption
	Contexts   ContextService
	Extensions ExtensionService
	Projects   ProjectService
	Sessions   SessionService
}

Client creates a struct with services and top level methods that help with interacting with the browserbase-unofficial API. You should not instantiate this client directly, and instead use the NewClient method instead.

func NewClient

func NewClient(opts ...option.RequestOption) (r Client)

NewClient generates a new client with the default option read from the environment (BROWSERBASE_UNOFFICIAL_API_KEY, BROWSERBASE_UNOFFICIAL_BASE_URL). The option passed in as arguments are applied after these default arguments, and all option will be passed down to the services and requests that this client makes.

func (*Client) Delete

func (r *Client) Delete(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Delete makes a DELETE request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Execute

func (r *Client) Execute(ctx context.Context, method string, path string, params any, res any, opts ...option.RequestOption) error

Execute makes a request with the given context, method, URL, request params, response, and request options. This is useful for hitting undocumented endpoints while retaining the base URL, auth, retries, and other options from the client.

If a byte slice or an io.Reader is supplied to params, it will be used as-is for the request body.

The params is by default serialized into the body using encoding/json. If your type implements a MarshalJSON function, it will be used instead to serialize the request. If a URLQuery method is implemented, the returned url.Values will be used as query strings to the url.

If your params struct uses param.Field, you must provide either [MarshalJSON], [URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use a struct uses param.Field without specifying how it is serialized.

Any "…Params" object defined in this library can be used as the request argument. Note that 'path' arguments will not be forwarded into the url.

The response body will be deserialized into the res variable, depending on its type:

  • A pointer to a *http.Response is populated by the raw response.
  • A pointer to a byte array will be populated with the contents of the request body.
  • A pointer to any other type uses this library's default JSON decoding, which respects UnmarshalJSON if it is defined on the type.
  • A nil value will not read the response body.

For even greater flexibility, see option.WithResponseInto and option.WithResponseBodyInto.

func (*Client) Get

func (r *Client) Get(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Get makes a GET request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Patch

func (r *Client) Patch(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Patch makes a PATCH request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Post

func (r *Client) Post(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Post makes a POST request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Put

func (r *Client) Put(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error

Put makes a PUT request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

type ContextGetResponse

type ContextGetResponse struct {
	ID        string    `json:"id,required"`
	CreatedAt time.Time `json:"createdAt,required" format:"date-time"`
	// The Project ID linked to the uploaded Context.
	ProjectID string    `json:"projectId,required"`
	UpdatedAt time.Time `json:"updatedAt,required" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID          respjson.Field
		CreatedAt   respjson.Field
		ProjectID   respjson.Field
		UpdatedAt   respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ContextGetResponse) RawJSON

func (r ContextGetResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*ContextGetResponse) UnmarshalJSON

func (r *ContextGetResponse) UnmarshalJSON(data []byte) error

type ContextNewParams

type ContextNewParams struct {
	// The Project ID. Can be found in
	// [Settings](https://www.browserbase.com/settings).
	ProjectID string `json:"projectId,required"`
	// contains filtered or unexported fields
}

func (ContextNewParams) MarshalJSON

func (r ContextNewParams) MarshalJSON() (data []byte, err error)

func (*ContextNewParams) UnmarshalJSON

func (r *ContextNewParams) UnmarshalJSON(data []byte) error

type ContextService

type ContextService struct {
	Options []option.RequestOption
}

ContextService contains methods and other services that help with interacting with the browserbase-unofficial API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewContextService method instead.

func NewContextService

func NewContextService(opts ...option.RequestOption) (r ContextService)

NewContextService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ContextService) Get

func (r *ContextService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *ContextGetResponse, err error)

Context

func (*ContextService) New

Create a Context

func (*ContextService) Update

func (r *ContextService) Update(ctx context.Context, id string, opts ...option.RequestOption) (res *CreateContextResponse, err error)

Update Context

type CreateContextResponse

type CreateContextResponse struct {
	ID string `json:"id,required"`
	// The cipher algorithm used to encrypt the user-data-directory. AES-256-CBC is
	// currently the only supported algorithm.
	CipherAlgorithm string `json:"cipherAlgorithm,required"`
	// The initialization vector size used to encrypt the user-data-directory.
	// [Read more about how to use it](/features/contexts).
	InitializationVectorSize int64 `json:"initializationVectorSize,required"`
	// The public key to encrypt the user-data-directory.
	PublicKey string `json:"publicKey,required"`
	// An upload URL to upload a custom user-data-directory.
	UploadURL string `json:"uploadUrl,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                       respjson.Field
		CipherAlgorithm          respjson.Field
		InitializationVectorSize respjson.Field
		PublicKey                respjson.Field
		UploadURL                respjson.Field
		ExtraFields              map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (CreateContextResponse) RawJSON

func (r CreateContextResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*CreateContextResponse) UnmarshalJSON

func (r *CreateContextResponse) UnmarshalJSON(data []byte) error

type Error

type Error = apierror.Error

type Extension

type Extension struct {
	ID        string    `json:"id,required"`
	CreatedAt time.Time `json:"createdAt,required" format:"date-time"`
	FileName  string    `json:"fileName,required"`
	// The Project ID linked to the uploaded Extension.
	ProjectID string    `json:"projectId,required"`
	UpdatedAt time.Time `json:"updatedAt,required" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID          respjson.Field
		CreatedAt   respjson.Field
		FileName    respjson.Field
		ProjectID   respjson.Field
		UpdatedAt   respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (Extension) RawJSON

func (r Extension) RawJSON() string

Returns the unmodified JSON received from the API

func (*Extension) UnmarshalJSON

func (r *Extension) UnmarshalJSON(data []byte) error

type ExtensionNewParams

type ExtensionNewParams struct {
	File io.Reader `json:"file,omitzero,required" format:"binary"`
	// contains filtered or unexported fields
}

func (ExtensionNewParams) MarshalMultipart

func (r ExtensionNewParams) MarshalMultipart() (data []byte, contentType string, err error)

type ExtensionService

type ExtensionService struct {
	Options []option.RequestOption
}

ExtensionService contains methods and other services that help with interacting with the browserbase-unofficial API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewExtensionService method instead.

func NewExtensionService

func NewExtensionService(opts ...option.RequestOption) (r ExtensionService)

NewExtensionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ExtensionService) Delete

func (r *ExtensionService) Delete(ctx context.Context, id string, opts ...option.RequestOption) (err error)

Delete Extension

func (*ExtensionService) Get

func (r *ExtensionService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Extension, err error)

Extension

func (*ExtensionService) New

func (r *ExtensionService) New(ctx context.Context, body ExtensionNewParams, opts ...option.RequestOption) (res *Extension, err error)

Upload an Extension

type Project

type Project struct {
	ID             string    `json:"id,required"`
	CreatedAt      time.Time `json:"createdAt,required" format:"date-time"`
	DefaultTimeout int64     `json:"defaultTimeout,required"`
	Name           string    `json:"name,required"`
	OwnerID        string    `json:"ownerId,required"`
	UpdatedAt      time.Time `json:"updatedAt,required" format:"date-time"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID             respjson.Field
		CreatedAt      respjson.Field
		DefaultTimeout respjson.Field
		Name           respjson.Field
		OwnerID        respjson.Field
		UpdatedAt      respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (Project) RawJSON

func (r Project) RawJSON() string

Returns the unmodified JSON received from the API

func (*Project) UnmarshalJSON

func (r *Project) UnmarshalJSON(data []byte) error

type ProjectService

type ProjectService struct {
	Options []option.RequestOption
}

ProjectService contains methods and other services that help with interacting with the browserbase-unofficial API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewProjectService method instead.

func NewProjectService

func NewProjectService(opts ...option.RequestOption) (r ProjectService)

NewProjectService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ProjectService) Get

func (r *ProjectService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Project, err error)

Project

func (*ProjectService) List

func (r *ProjectService) List(ctx context.Context, opts ...option.RequestOption) (res *[]Project, err error)

List all projects

func (*ProjectService) Usage

func (r *ProjectService) Usage(ctx context.Context, id string, opts ...option.RequestOption) (res *ProjectUsageResponse, err error)

Project Usage

type ProjectUsageResponse

type ProjectUsageResponse struct {
	BrowserMinutes int64 `json:"browserMinutes,required"`
	ProxyBytes     int64 `json:"proxyBytes,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		BrowserMinutes respjson.Field
		ProxyBytes     respjson.Field
		ExtraFields    map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (ProjectUsageResponse) RawJSON

func (r ProjectUsageResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*ProjectUsageResponse) UnmarshalJSON

func (r *ProjectUsageResponse) UnmarshalJSON(data []byte) error

type Region

type Region string
const (
	RegionUsWest2      Region = "us-west-2"
	RegionUsEast1      Region = "us-east-1"
	RegionEuCentral1   Region = "eu-central-1"
	RegionApSoutheast1 Region = "ap-southeast-1"
)

type Session

type Session struct {
	ID        string    `json:"id,required"`
	CreatedAt time.Time `json:"createdAt,required" format:"date-time"`
	ExpiresAt time.Time `json:"expiresAt,required" format:"date-time"`
	// Indicates if the Session was created to be kept alive upon disconnections
	KeepAlive bool `json:"keepAlive,required"`
	// The Project ID linked to the Session.
	ProjectID string `json:"projectId,required"`
	// Bytes used via the [Proxy](/features/stealth-mode#proxies-and-residential-ips)
	ProxyBytes int64 `json:"proxyBytes,required"`
	// The region where the Session is running.
	//
	// Any of "us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1".
	Region    Region    `json:"region,required"`
	StartedAt time.Time `json:"startedAt,required" format:"date-time"`
	// Any of "RUNNING", "ERROR", "TIMED_OUT", "COMPLETED".
	Status    SessionStatus `json:"status,required"`
	UpdatedAt time.Time     `json:"updatedAt,required" format:"date-time"`
	// CPU used by the Session
	AvgCPUUsage int64 `json:"avgCpuUsage"`
	// Optional. The Context linked to the Session.
	ContextID string    `json:"contextId"`
	EndedAt   time.Time `json:"endedAt" format:"date-time"`
	// Memory used by the Session
	MemoryUsage int64 `json:"memoryUsage"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID          respjson.Field
		CreatedAt   respjson.Field
		ExpiresAt   respjson.Field
		KeepAlive   respjson.Field
		ProjectID   respjson.Field
		ProxyBytes  respjson.Field
		Region      respjson.Field
		StartedAt   respjson.Field
		Status      respjson.Field
		UpdatedAt   respjson.Field
		AvgCPUUsage respjson.Field
		ContextID   respjson.Field
		EndedAt     respjson.Field
		MemoryUsage respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (Session) RawJSON

func (r Session) RawJSON() string

Returns the unmodified JSON received from the API

func (*Session) UnmarshalJSON

func (r *Session) UnmarshalJSON(data []byte) error

type SessionDebugResponse

type SessionDebugResponse struct {
	DebuggerFullscreenURL string                     `json:"debuggerFullscreenUrl,required" format:"uri"`
	DebuggerURL           string                     `json:"debuggerUrl,required" format:"uri"`
	Pages                 []SessionDebugResponsePage `json:"pages,required"`
	WsURL                 string                     `json:"wsUrl,required" format:"uri"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		DebuggerFullscreenURL respjson.Field
		DebuggerURL           respjson.Field
		Pages                 respjson.Field
		WsURL                 respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SessionDebugResponse) RawJSON

func (r SessionDebugResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*SessionDebugResponse) UnmarshalJSON

func (r *SessionDebugResponse) UnmarshalJSON(data []byte) error

type SessionDebugResponsePage

type SessionDebugResponsePage struct {
	ID                    string `json:"id,required"`
	DebuggerFullscreenURL string `json:"debuggerFullscreenUrl,required" format:"uri"`
	DebuggerURL           string `json:"debuggerUrl,required" format:"uri"`
	FaviconURL            string `json:"faviconUrl,required" format:"uri"`
	Title                 string `json:"title,required"`
	URL                   string `json:"url,required" format:"uri"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                    respjson.Field
		DebuggerFullscreenURL respjson.Field
		DebuggerURL           respjson.Field
		FaviconURL            respjson.Field
		Title                 respjson.Field
		URL                   respjson.Field
		ExtraFields           map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SessionDebugResponsePage) RawJSON

func (r SessionDebugResponsePage) RawJSON() string

Returns the unmodified JSON received from the API

func (*SessionDebugResponsePage) UnmarshalJSON

func (r *SessionDebugResponsePage) UnmarshalJSON(data []byte) error

type SessionListParams

type SessionListParams struct {
	// Any of "RUNNING", "ERROR", "TIMED_OUT", "COMPLETED".
	Status SessionStatus `query:"status,omitzero" json:"-"`
	// contains filtered or unexported fields
}

func (SessionListParams) URLQuery

func (r SessionListParams) URLQuery() (v url.Values, err error)

URLQuery serializes SessionListParams's query parameters as `url.Values`.

type SessionLogsResponse

type SessionLogsResponse struct {
	EventID   string `json:"eventId,required"`
	Method    string `json:"method,required"`
	PageID    int64  `json:"pageId,required"`
	SessionID string `json:"sessionId,required"`
	// milliseconds that have elapsed since the UNIX epoch
	Timestamp int64                       `json:"timestamp,required"`
	FrameID   string                      `json:"frameId"`
	LoaderID  string                      `json:"loaderId"`
	Request   SessionLogsResponseRequest  `json:"request"`
	Response  SessionLogsResponseResponse `json:"response"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		EventID     respjson.Field
		Method      respjson.Field
		PageID      respjson.Field
		SessionID   respjson.Field
		Timestamp   respjson.Field
		FrameID     respjson.Field
		LoaderID    respjson.Field
		Request     respjson.Field
		Response    respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SessionLogsResponse) RawJSON

func (r SessionLogsResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*SessionLogsResponse) UnmarshalJSON

func (r *SessionLogsResponse) UnmarshalJSON(data []byte) error

type SessionLogsResponseRequest

type SessionLogsResponseRequest struct {
	Params  map[string]any `json:"params,required"`
	RawBody string         `json:"rawBody,required"`
	// milliseconds that have elapsed since the UNIX epoch
	Timestamp int64 `json:"timestamp,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Params      respjson.Field
		RawBody     respjson.Field
		Timestamp   respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SessionLogsResponseRequest) RawJSON

func (r SessionLogsResponseRequest) RawJSON() string

Returns the unmodified JSON received from the API

func (*SessionLogsResponseRequest) UnmarshalJSON

func (r *SessionLogsResponseRequest) UnmarshalJSON(data []byte) error

type SessionLogsResponseResponse

type SessionLogsResponseResponse struct {
	RawBody string         `json:"rawBody,required"`
	Result  map[string]any `json:"result,required"`
	// milliseconds that have elapsed since the UNIX epoch
	Timestamp int64 `json:"timestamp,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		RawBody     respjson.Field
		Result      respjson.Field
		Timestamp   respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SessionLogsResponseResponse) RawJSON

func (r SessionLogsResponseResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*SessionLogsResponseResponse) UnmarshalJSON

func (r *SessionLogsResponseResponse) UnmarshalJSON(data []byte) error

type SessionNewParams

type SessionNewParams struct {
	// The Project ID. Can be found in
	// [Settings](https://www.browserbase.com/settings).
	ProjectID string `json:"projectId,required"`
	// The uploaded Extension ID. See
	// [Upload Extension](/reference/api/upload-an-extension).
	ExtensionID param.Opt[string] `json:"extensionId,omitzero"`
	// Set to true to keep the session alive even after disconnections. This is
	// available on the Startup plan only.
	KeepAlive param.Opt[bool] `json:"keepAlive,omitzero"`
	// Duration in seconds after which the session will automatically end. Defaults to
	// the Project's `defaultTimeout`.
	Timeout         param.Opt[int64]                `json:"timeout,omitzero"`
	BrowserSettings SessionNewParamsBrowserSettings `json:"browserSettings,omitzero"`
	// Proxy configuration. Can be true for default proxy, or an array of proxy
	// configurations.
	Proxies any `json:"proxies,omitzero"`
	// The region where the Session should run.
	//
	// Any of "us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1".
	Region Region `json:"region,omitzero"`
	// contains filtered or unexported fields
}

func (SessionNewParams) MarshalJSON

func (r SessionNewParams) MarshalJSON() (data []byte, err error)

func (*SessionNewParams) UnmarshalJSON

func (r *SessionNewParams) UnmarshalJSON(data []byte) error

type SessionNewParamsBrowserSettings

type SessionNewParamsBrowserSettings struct {
	// Enable or disable ad blocking in the browser. Defaults to `false`.
	BlockAds param.Opt[bool] `json:"blockAds,omitzero"`
	// The uploaded Extension ID. See
	// [Upload Extension](/reference/api/upload-an-extension).
	ExtensionID param.Opt[string] `json:"extensionId,omitzero"`
	// Enable or disable session logging. Defaults to `true`.
	LogSession param.Opt[bool] `json:"logSession,omitzero"`
	// Enable or disable session recording. Defaults to `true`.
	RecordSession param.Opt[bool] `json:"recordSession,omitzero"`
	// Enable or disable captcha solving in the browser. Defaults to `true`.
	SolveCaptchas param.Opt[bool]                        `json:"solveCaptchas,omitzero"`
	Context       SessionNewParamsBrowserSettingsContext `json:"context,omitzero"`
	// See usage examples
	// [in the Stealth Mode page](/features/stealth-mode#fingerprinting).
	Fingerprint SessionNewParamsBrowserSettingsFingerprint `json:"fingerprint,omitzero"`
	Viewport    SessionNewParamsBrowserSettingsViewport    `json:"viewport,omitzero"`
	// contains filtered or unexported fields
}

func (SessionNewParamsBrowserSettings) MarshalJSON

func (r SessionNewParamsBrowserSettings) MarshalJSON() (data []byte, err error)

func (*SessionNewParamsBrowserSettings) UnmarshalJSON

func (r *SessionNewParamsBrowserSettings) UnmarshalJSON(data []byte) error

type SessionNewParamsBrowserSettingsContext

type SessionNewParamsBrowserSettingsContext struct {
	// The Context ID.
	ID string `json:"id,required"`
	// Whether or not to persist the context after browsing. Defaults to `false`.
	Persist param.Opt[bool] `json:"persist,omitzero"`
	// contains filtered or unexported fields
}

The property ID is required.

func (SessionNewParamsBrowserSettingsContext) MarshalJSON

func (r SessionNewParamsBrowserSettingsContext) MarshalJSON() (data []byte, err error)

func (*SessionNewParamsBrowserSettingsContext) UnmarshalJSON

func (r *SessionNewParamsBrowserSettingsContext) UnmarshalJSON(data []byte) error

type SessionNewParamsBrowserSettingsFingerprint

type SessionNewParamsBrowserSettingsFingerprint struct {
	// Any of "chrome", "edge", "firefox", "safari".
	Browsers []string `json:"browsers,omitzero"`
	// Any of "desktop", "mobile".
	Devices []string `json:"devices,omitzero"`
	// Any of 1, 2.
	HTTPVersion float64 `json:"httpVersion,omitzero"`
	// Full list of locales is available
	// [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language).
	Locales []string `json:"locales,omitzero"`
	// Note: `operatingSystems` set to `ios` or `android` requires `devices` to include
	// `"mobile"`.
	//
	// Any of "android", "ios", "linux", "macos", "windows".
	OperatingSystems []string                                         `json:"operatingSystems,omitzero"`
	Screen           SessionNewParamsBrowserSettingsFingerprintScreen `json:"screen,omitzero"`
	// contains filtered or unexported fields
}

See usage examples [in the Stealth Mode page](/features/stealth-mode#fingerprinting).

func (SessionNewParamsBrowserSettingsFingerprint) MarshalJSON

func (r SessionNewParamsBrowserSettingsFingerprint) MarshalJSON() (data []byte, err error)

func (*SessionNewParamsBrowserSettingsFingerprint) UnmarshalJSON

func (r *SessionNewParamsBrowserSettingsFingerprint) UnmarshalJSON(data []byte) error

type SessionNewParamsBrowserSettingsFingerprintScreen

type SessionNewParamsBrowserSettingsFingerprintScreen struct {
	MaxHeight param.Opt[int64] `json:"maxHeight,omitzero"`
	MaxWidth  param.Opt[int64] `json:"maxWidth,omitzero"`
	MinHeight param.Opt[int64] `json:"minHeight,omitzero"`
	MinWidth  param.Opt[int64] `json:"minWidth,omitzero"`
	// contains filtered or unexported fields
}

func (SessionNewParamsBrowserSettingsFingerprintScreen) MarshalJSON

func (r SessionNewParamsBrowserSettingsFingerprintScreen) MarshalJSON() (data []byte, err error)

func (*SessionNewParamsBrowserSettingsFingerprintScreen) UnmarshalJSON

type SessionNewParamsBrowserSettingsViewport

type SessionNewParamsBrowserSettingsViewport struct {
	Height param.Opt[int64] `json:"height,omitzero"`
	Width  param.Opt[int64] `json:"width,omitzero"`
	// contains filtered or unexported fields
}

func (SessionNewParamsBrowserSettingsViewport) MarshalJSON

func (r SessionNewParamsBrowserSettingsViewport) MarshalJSON() (data []byte, err error)

func (*SessionNewParamsBrowserSettingsViewport) UnmarshalJSON

func (r *SessionNewParamsBrowserSettingsViewport) UnmarshalJSON(data []byte) error

type SessionNewResponse

type SessionNewResponse struct {
	ID string `json:"id,required"`
	// WebSocket URL to connect to the Session.
	ConnectURL string    `json:"connectUrl,required" format:"uri"`
	CreatedAt  time.Time `json:"createdAt,required" format:"date-time"`
	ExpiresAt  time.Time `json:"expiresAt,required" format:"date-time"`
	// Indicates if the Session was created to be kept alive upon disconnections
	KeepAlive bool `json:"keepAlive,required"`
	// The Project ID linked to the Session.
	ProjectID string `json:"projectId,required"`
	// Bytes used via the [Proxy](/features/stealth-mode#proxies-and-residential-ips)
	ProxyBytes int64 `json:"proxyBytes,required"`
	// The region where the Session is running.
	//
	// Any of "us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1".
	Region Region `json:"region,required"`
	// HTTP URL to connect to the Session.
	SeleniumRemoteURL string `json:"seleniumRemoteUrl,required" format:"uri"`
	// Signing key to use when connecting to the Session via HTTP.
	SigningKey string    `json:"signingKey,required"`
	StartedAt  time.Time `json:"startedAt,required" format:"date-time"`
	// Any of "RUNNING", "ERROR", "TIMED_OUT", "COMPLETED".
	Status    SessionStatus `json:"status,required"`
	UpdatedAt time.Time     `json:"updatedAt,required" format:"date-time"`
	// CPU used by the Session
	AvgCPUUsage int64 `json:"avgCpuUsage"`
	// Optional. The Context linked to the Session.
	ContextID string    `json:"contextId"`
	EndedAt   time.Time `json:"endedAt" format:"date-time"`
	// Memory used by the Session
	MemoryUsage int64 `json:"memoryUsage"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID                respjson.Field
		ConnectURL        respjson.Field
		CreatedAt         respjson.Field
		ExpiresAt         respjson.Field
		KeepAlive         respjson.Field
		ProjectID         respjson.Field
		ProxyBytes        respjson.Field
		Region            respjson.Field
		SeleniumRemoteURL respjson.Field
		SigningKey        respjson.Field
		StartedAt         respjson.Field
		Status            respjson.Field
		UpdatedAt         respjson.Field
		AvgCPUUsage       respjson.Field
		ContextID         respjson.Field
		EndedAt           respjson.Field
		MemoryUsage       respjson.Field
		ExtraFields       map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SessionNewResponse) RawJSON

func (r SessionNewResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*SessionNewResponse) UnmarshalJSON

func (r *SessionNewResponse) UnmarshalJSON(data []byte) error

type SessionNewUploadsParams

type SessionNewUploadsParams struct {
	File io.Reader `json:"file,omitzero,required" format:"binary"`
	// contains filtered or unexported fields
}

func (SessionNewUploadsParams) MarshalMultipart

func (r SessionNewUploadsParams) MarshalMultipart() (data []byte, contentType string, err error)

type SessionNewUploadsResponse

type SessionNewUploadsResponse struct {
	Message string `json:"message,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		Message     respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SessionNewUploadsResponse) RawJSON

func (r SessionNewUploadsResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*SessionNewUploadsResponse) UnmarshalJSON

func (r *SessionNewUploadsResponse) UnmarshalJSON(data []byte) error

type SessionRecordingResponse

type SessionRecordingResponse struct {
	ID string `json:"id,required"`
	// See
	// [rrweb documentation](https://github.com/rrweb-io/rrweb/blob/master/docs/recipes/dive-into-event.md).
	Data      map[string]any `json:"data,required"`
	SessionID string         `json:"sessionId,required"`
	// milliseconds that have elapsed since the UNIX epoch
	Timestamp int64 `json:"timestamp,required"`
	Type      int64 `json:"type,required"`
	// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
	JSON struct {
		ID          respjson.Field
		Data        respjson.Field
		SessionID   respjson.Field
		Timestamp   respjson.Field
		Type        respjson.Field
		ExtraFields map[string]respjson.Field
		// contains filtered or unexported fields
	} `json:"-"`
}

func (SessionRecordingResponse) RawJSON

func (r SessionRecordingResponse) RawJSON() string

Returns the unmodified JSON received from the API

func (*SessionRecordingResponse) UnmarshalJSON

func (r *SessionRecordingResponse) UnmarshalJSON(data []byte) error

type SessionService

type SessionService struct {
	Options []option.RequestOption
}

SessionService contains methods and other services that help with interacting with the browserbase-unofficial API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewSessionService method instead.

func NewSessionService

func NewSessionService(opts ...option.RequestOption) (r SessionService)

NewSessionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*SessionService) Debug

func (r *SessionService) Debug(ctx context.Context, id string, opts ...option.RequestOption) (res *SessionDebugResponse, err error)

Session Live URLs

func (*SessionService) Downloads

func (r *SessionService) Downloads(ctx context.Context, id string, opts ...option.RequestOption) (res *http.Response, err error)

Session Downloads

func (*SessionService) Get

func (r *SessionService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Session, err error)

Session

func (*SessionService) List

func (r *SessionService) List(ctx context.Context, query SessionListParams, opts ...option.RequestOption) (res *[]Session, err error)

List Sessions

func (*SessionService) Logs

func (r *SessionService) Logs(ctx context.Context, id string, opts ...option.RequestOption) (res *[]SessionLogsResponse, err error)

Session Logs

func (*SessionService) New

Create a Session

func (*SessionService) NewUploads

Create Session Uploads

func (*SessionService) Recording

func (r *SessionService) Recording(ctx context.Context, id string, opts ...option.RequestOption) (res *[]SessionRecordingResponse, err error)

Session Recording

func (*SessionService) Update

func (r *SessionService) Update(ctx context.Context, id string, body SessionUpdateParams, opts ...option.RequestOption) (res *Session, err error)

Update Session

type SessionStatus

type SessionStatus string
const (
	SessionStatusRunning   SessionStatus = "RUNNING"
	SessionStatusError     SessionStatus = "ERROR"
	SessionStatusTimedOut  SessionStatus = "TIMED_OUT"
	SessionStatusCompleted SessionStatus = "COMPLETED"
)

type SessionUpdateParams

type SessionUpdateParams struct {
	// The Project ID. Can be found in
	// [Settings](https://www.browserbase.com/settings).
	ProjectID string `json:"projectId,required"`
	// Set to `REQUEST_RELEASE` to request that the session complete. Use before
	// session's timeout to avoid additional charges.
	//
	// Any of "REQUEST_RELEASE".
	Status SessionUpdateParamsStatus `json:"status,omitzero,required"`
	// contains filtered or unexported fields
}

func (SessionUpdateParams) MarshalJSON

func (r SessionUpdateParams) MarshalJSON() (data []byte, err error)

func (*SessionUpdateParams) UnmarshalJSON

func (r *SessionUpdateParams) UnmarshalJSON(data []byte) error

type SessionUpdateParamsStatus

type SessionUpdateParamsStatus string

Set to `REQUEST_RELEASE` to request that the session complete. Use before session's timeout to avoid additional charges.

const (
	SessionUpdateParamsStatusRequestRelease SessionUpdateParamsStatus = "REQUEST_RELEASE"
)

Directories

Path Synopsis
encoding/json
Package json implements encoding and decoding of JSON as defined in RFC 7159.
Package json implements encoding and decoding of JSON as defined in RFC 7159.
encoding/json/shims
This package provides shims over Go 1.2{2,3} APIs which are missing from Go 1.22, and used by the Go 1.24 encoding/json package.
This package provides shims over Go 1.2{2,3} APIs which are missing from Go 1.22, and used by the Go 1.24 encoding/json package.
packages
shared

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL