Skip to content
31 changes: 31 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,37 @@ All notable changes to the Apify Go client are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.17.0] - 2026-11-27

### Added

- `KeyValueStoreClient.SetRecordStream` and `SetRecordStreamWithEncoding`, `ActorClient.StartStream`
and `CallStream`, and `TaskClient.StartStream` and `CallStream`, which send an `io.Reader` as the
record value or the run input, so a large body is not held in memory. The stream is sent once,
without compression or retries, and a redirect is an error. A task input stream holds a JSON
object.
- An `io.Reader` as `ActorServerRequestOptions.Body`, sent the same way. Before, it was serialized
as JSON.
- `ActorStoreListItem.Categories`, `Stats` (the new `StoreActorStats`) and `IsVerified`.

### Changed

- `categories`, `stats` and `isVerified` of a Store Actor are no longer in
`ActorStoreListItem.Extra`.
- `StoreCollectionClient.Iterate` with `StoreListOptions.Search` set makes one request and yields
each Actor once. The API ignores the offset for a search, so paging through it repeated the same
Actors without end.
- `ActorVersionCollectionClient.Create` and `ActorVersionClient.Update` use the long timeout tier,
since a version can carry its source files.
- Updated the documentation of `StoreListOptions` to the OpenAPI specification: the single-page
search, the comma-separated `Category` IDs, and `IncludeUnrunnableActors`, `ResponseFormat` and
`AllowsAgenticUsers`.
- Added the `APIFY_AI` run origin to the `LastRunOptions.Origin` examples.

### Deprecated

- `StoreListOptions.SortBy`, which the API ignores.

## [0.16.2] - 2026-11-24

### Security
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,13 @@ the request.
## Custom HTTP transport

The transport is replaceable. Implement `HTTPBackend` (a single `Do` method) to integrate a
custom client, proxy, or test double, and pass it with `WithHTTPBackend`. A backend that follows
custom client, proxy, or test double, and pass it with `WithHTTPBackend`. The backend must close
`req.Body` once it is done with it, also when it fails, as an `http.RoundTripper` does: the client
relies on that to close the stream body of a request that was sent. A backend that follows
redirects must not follow them for a request that `apify.FollowsRedirects(req)` reports false for,
as the requests to a [Server Actor](docs/server_actors.md) carry a token meant for one host only,
and a redirect to another host would send it there:
and a redirect to another host would send it there. The requests with a stream body (such as
`SetRecordStream`) are the same, since a redirect cannot replay a stream:

```go
package main
Expand All @@ -266,7 +269,8 @@ func (b *myBackend) Do(req *http.Request) (*http.Response, error) {
if apify.FollowsRedirects(req) {
return b.inner.Do(req)
}
// This request carries a token meant for one host only, so a redirect is returned as it is.
// This request carries a token meant for one host only, or a stream body that a redirect cannot
// replay, so a redirect is returned as it is.
client := *b.inner
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return client.Do(req)
Expand Down
56 changes: 47 additions & 9 deletions actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"sync"
"time"
Expand Down Expand Up @@ -42,10 +43,10 @@ type ActorStartOptions struct {
// A run that requests more memory than the account's limit is rejected with
// actor-memory-limit-exceeded and never starts, so WaitForResourcesIndefinitely retries it forever.
WaitForResources *int64
// Log configures the redirection of the run's log that [ActorClient.Call] and
// [ActorClient.CallRaw] do while they wait (see [StreamedLog]). Nil redirects it to os.Stderr
// with the default prefix; set Log.Disabled to turn the redirection off. Start and StartRaw
// ignore it.
// Log configures the redirection of the run's log that [ActorClient.Call],
// [ActorClient.CallRaw] and [ActorClient.CallStream] do while they wait (see [StreamedLog]).
// Nil redirects it to os.Stderr with the default prefix; set Log.Disabled to turn the
// redirection off. Start, StartRaw and StartStream ignore it.
Log *StreamedLogOptions
}

Expand Down Expand Up @@ -150,6 +151,18 @@ func (c *ActorClient) StartRaw(ctx context.Context, input []byte, options ActorS
return c.startWithBody(ctx, input, "application/octet-stream", options, c.startTimeout(options))
}

// StartStream starts the Actor with a stream as its input, for a large input that is not held in
// memory, such as a file. The input has the content type "application/octet-stream" unless
// options.ContentType is set.
//
// The stream is sent as it is, once: the request is neither compressed nor retried, since a retry
// would send what the first attempt left of the stream, and a redirect comes back as an error.
// Hence options.WaitForResources is ignored, as the start is never retried. The client closes the
// stream when the call ends, if it is an [io.Closer].
func (c *ActorClient) StartStream(ctx context.Context, input io.Reader, options ActorStartOptions) (ActorRun, error) {
return c.startWithStream(ctx, input, options, c.startTimeout(options))
}

// startTimeout is the timeout of a start request: the "medium" tier, extended to cover the time
// the API may hold the response for options.WaitForFinish.
func (c *ActorClient) startTimeout(options ActorStartOptions) time.Duration {
Expand All @@ -171,6 +184,18 @@ func (c *ActorClient) startWithBody(ctx context.Context, body []byte, defaultCon
})
}

// startWithStream starts the Actor with a streamed input of the content type from
// options.ContentType, or application/octet-stream.
func (c *ActorClient) startWithStream(ctx context.Context, input io.Reader, options ActorStartOptions, timeout time.Duration) (ActorRun, error) {
params := NewQueryParams()
options.apply(params)
contentType := "application/octet-stream"
if options.ContentType != nil && *options.ContentType != "" {
contentType = *options.ContentType
}
return postStream[ActorRun](ctx, c.ctx, "runs", params, input, contentType, timeout)
}

// Call starts the Actor and waits for it to finish. waitSecs bounds the wait, and nil waits
// indefinitely. It returns the finished run, or the running run if the wait ran out.
//
Expand All @@ -183,18 +208,31 @@ func (c *ActorClient) Call(ctx context.Context, input any, options ActorStartOpt
if err != nil {
return ActorRun{}, err
}
return c.callWithBody(ctx, body, contentTypeJSON, options, waitSecs)
return c.callAndWait(ctx, options, waitSecs, func(timeout time.Duration) (ActorRun, error) {
return c.startWithBody(ctx, body, contentTypeJSON, options, timeout)
})
}

// CallRaw starts the Actor with a raw request body ([ActorClient.StartRaw]) and waits for it to
// finish, exactly like [ActorClient.Call] but for a non-JSON input.
func (c *ActorClient) CallRaw(ctx context.Context, input []byte, options ActorStartOptions, waitSecs *int64) (ActorRun, error) {
return c.callWithBody(ctx, input, "application/octet-stream", options, waitSecs)
return c.callAndWait(ctx, options, waitSecs, func(timeout time.Duration) (ActorRun, error) {
return c.startWithBody(ctx, input, "application/octet-stream", options, timeout)
})
}

// CallStream starts the Actor with a stream as its input ([ActorClient.StartStream]) and waits
// for it to finish, exactly like [ActorClient.Call] but for a streamed input.
func (c *ActorClient) CallStream(ctx context.Context, input io.Reader, options ActorStartOptions, waitSecs *int64) (ActorRun, error) {
return c.callAndWait(ctx, options, waitSecs, func(timeout time.Duration) (ActorRun, error) {
return c.startWithStream(ctx, input, options, timeout)
})
}

// callWithBody is the shared implementation of Call and CallRaw.
func (c *ActorClient) callWithBody(ctx context.Context, body []byte, defaultContentType string, options ActorStartOptions, waitSecs *int64) (ActorRun, error) {
run, err := c.startWithBody(ctx, body, defaultContentType, options, noRequestTimeout)
// callAndWait is the shared implementation of Call, CallRaw and CallStream: it starts the run with
// start, which gets the timeout of the start request, and waits for it to finish.
func (c *ActorClient) callAndWait(ctx context.Context, options ActorStartOptions, waitSecs *int64, start func(timeout time.Duration) (ActorRun, error)) (ActorRun, error) {
run, err := start(noRequestTimeout)
if err != nil {
return ActorRun{}, err
}
Expand Down
20 changes: 16 additions & 4 deletions actor_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ type ActorServerRequestOptions struct {
// removes the client's header of that name.
Headers http.Header
// Body is the request body. A string or []byte is sent as it is, without a Content-Type
// unless Headers sets one. A [json.RawMessage] and any other value are sent as JSON, with
// unless Headers sets one. An [io.Reader] is a stream, sent the same way but only once: the
// request is neither compressed nor retried on 429 or 503, since a retry would send what the
// first attempt left of the stream, and the client closes it when the call ends, if it is an
// [io.Closer]. A [json.RawMessage] and any other value are sent as JSON, with
// Content-Type application/json unless Headers sets one.
Body any
// ParentRequestID is the X-Actor-Request-ID header of the request that the calling Server
Expand Down Expand Up @@ -341,16 +344,23 @@ func (c *ActorServerClient) RequestStream(ctx context.Context, path string, opti

// send validates the options, resolves the server URL and sends the request.
func (c *ActorServerClient) send(ctx context.Context, path string, options ActorServerRequestOptions, stream bool) (*serverResponse, error) {
bodyStream, _ := options.Body.(io.Reader)
method := strings.ToUpper(options.Method)
if method == "" {
method = http.MethodGet
}
if !httpMethods[method] || (options.Method != "" && options.Method != method) {
closeStream(bodyStream)
return nil, fmt.Errorf("ActorServerRequestOptions.Method: unknown HTTP method %q", options.Method)
}
body, contentType, err := encodeServerBody(options.Body)
if err != nil {
return nil, err
// A stream is sent as it is, so it is not encoded and its request is not retried.
var body []byte
var contentType string
if bodyStream == nil {
var err error
if body, contentType, err = encodeServerBody(options.Body); err != nil {
return nil, err
}
}
var compressors []requestCompressor
if options.Compression != nil {
Expand All @@ -359,6 +369,7 @@ func (c *ActorServerClient) send(ctx context.Context, path string, options Actor

serverURL, err := c.GetURL(ctx)
if err != nil {
closeStream(bodyStream)
return nil, err
}
headers := options.Headers
Expand All @@ -369,6 +380,7 @@ func (c *ActorServerClient) send(ctx context.Context, path string, options Actor
method: method,
url: serverRequestURL(serverURL, path, options.Params),
body: body,
bodyStream: bodyStream,
contentType: contentType,
headers: headers,
compressors: compressors,
Expand Down
21 changes: 21 additions & 0 deletions actor_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -817,3 +817,24 @@ func TestActorVersionCarriesTheActorPath(t *testing.T) {
t.Fatalf("a null actorPath must decode to nil: %v, %v", v.ActorPath, err)
}
}

// A stream body is sent as it is, once: not compressed, and not retried on 429 or 503, since a
// retry would send what the first attempt left of the stream.
func TestActorServerRequestSendsAStreamBodyOnce(t *testing.T) {
f := newServerFixture(t)
f.flaky = []int{503}
server := f.client(WithMaxRetries(2), WithMinDelayBetweenRetries(time.Millisecond)).Actor(serverTestActorID).Server()
resp, err := server.Request(context.Background(), "/flaky", ActorServerRequestOptions{
Method: "POST", Body: strings.NewReader(compressibleBody), Compression: Ptr(RequestCompressionGzip),
})
if err != nil || resp.StatusCode != 503 {
t.Fatalf("expected the 503 to be returned without a retry: %+v, %v", resp, err)
}
reqs := f.requests(serverTestPrefix + "/")
if len(reqs) != 1 || string(reqs[0].body) != compressibleBody || reqs[0].header.Get("Content-Encoding") != "" {
t.Fatalf("expected one uncompressed request with the whole stream, got %d", len(reqs))
}
if got := reqs[0].header.Get("Content-Type"); got != "" {
t.Errorf("a stream has no Content-Type of its own, got %q", got)
}
}
10 changes: 6 additions & 4 deletions actor_version.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ func (c *ActorVersionCollectionClient) Iterate() *ListIterator[ActorVersion] {
return newUnpaginatedIterator(c.List)
}

// Create creates a new Actor version. version is any JSON-serializable version definition.
// Create creates a new Actor version. version is any JSON-serializable version definition. The
// request uses the long timeout tier, since the version can carry its source files.
func (c *ActorVersionCollectionClient) Create(ctx context.Context, version any) (ActorVersion, error) {
return createResource[ActorVersion](ctx, c.ctx, NewQueryParams(), version, c.ctx.shortTimeout())
return createResource[ActorVersion](ctx, c.ctx, NewQueryParams(), version, c.ctx.longTimeout())
}

// ActorVersionClient is a client for a specific Actor version
Expand All @@ -46,9 +47,10 @@ func (c *ActorVersionClient) Get(ctx context.Context) (ActorVersion, bool, error
return getResource[ActorVersion](ctx, c.ctx, "", NewQueryParams())
}

// Update updates the version with the given fields and returns the updated object.
// Update updates the version with the given fields and returns the updated object. The request
// uses the long timeout tier, since the version can carry its source files.
func (c *ActorVersionClient) Update(ctx context.Context, newFields any) (ActorVersion, error) {
return updateResource[ActorVersion](ctx, c.ctx, "", newFields)
return updateResourceWithTimeout[ActorVersion](ctx, c.ctx, "", newFields, c.ctx.longTimeout())
}

// Delete deletes the version.
Expand Down
36 changes: 36 additions & 0 deletions base.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,30 @@ func postWithBody[T any](ctx context.Context, c *resourceContext, subPath string
return parseDataEnvelope[T](resp.body)
}

// closeStream closes body if it is an [io.Closer], as the HTTP transport does for a request it
// sent, so that a stream is closed whether or not the call got as far as sending it.
func closeStream(body io.Reader) {
if closer, ok := body.(io.Closer); ok {
_ = closer.Close()
}
}

// postStream performs a POST with a stream as the body and unwraps the data envelope. The body is
// sent once (see [httpClient.callStream]).
func postStream[T any](ctx context.Context, c *resourceContext, subPath string, params *QueryParams, body io.Reader, contentType string, timeout time.Duration) (T, error) {
var zero T
if c.idErr != nil {
closeStream(body)
return zero, c.idErr
}
url := c.mergedParams(params).applyToURL(c.subURL(subPath))
resp, err := c.http.callStream(ctx, http.MethodPost, url, body, contentType, "", timeout)
if err != nil {
return zero, err
}
return parseDataEnvelope[T](resp.body)
}

// deleteWithBody performs a DELETE with a JSON body and unwraps the data envelope.
func deleteWithBody[T any](ctx context.Context, c *resourceContext, subPath string, params *QueryParams, body any) (T, error) {
var zero T
Expand Down Expand Up @@ -387,6 +411,18 @@ func putRawWithEncoding(ctx context.Context, c *resourceContext, subPath string,
return err
}

// putStream performs a PUT with a stream as the body. The body is sent once and as it is, under
// contentEncoding when that is not empty (see [httpClient.callStream]).
func putStream(ctx context.Context, c *resourceContext, subPath string, params *QueryParams, body io.Reader, contentType, contentEncoding string) error {
if c.idErr != nil {
closeStream(body)
return c.idErr
}
url := c.mergedParams(params).applyToURL(c.subURL(subPath))
_, err := c.http.callStream(ctx, http.MethodPut, url, body, contentType, contentEncoding, c.longTimeout())
return err
}

// streamRaw sends a GET request and returns the response body unread, with the response headers.
// The request is not retried, and the caller closes the body.
//
Expand Down
6 changes: 4 additions & 2 deletions docs/actors.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ The `Actor` value returned by `Get`/`Create`/`Update` and listed by `List`:
| `StartRaw(ctx, input []byte, ActorStartOptions) (ActorRun, error)` | Like `Start`, but sends `input` as a raw request body (no JSON serialization) — for a non-JSON input such as a ZIP archive, paired with `ActorStartOptions.ContentType`. |
| `Call(ctx, input any, ActorStartOptions, waitSecs *int64) (ActorRun, error)` | Start and wait for the run to finish, redirecting the run's log to `os.Stderr` while it waits (see `ActorStartOptions.Log`). `waitSecs` bounds the client-side wait; pass `nil` to wait indefinitely (until the run reaches a terminal state). Neither the start request nor the polls have a client-side timeout: `ctx` bounds the call. |
| `CallRaw(ctx, input []byte, ActorStartOptions, waitSecs *int64) (ActorRun, error)` | `StartRaw` followed by waiting for the run to finish, like `Call`. |
| `StartStream(ctx, input io.Reader, ActorStartOptions) (ActorRun, error)` | Like `StartRaw`, but reads the input from a stream, such as a file, so it is not held in memory. The stream is sent once: the request is not compressed or retried (`WaitForResources` is ignored) and a redirect is an error. The client closes the stream when the call ends, if it is an `io.Closer`. |
| `CallStream(ctx, input io.Reader, ActorStartOptions, waitSecs *int64) (ActorRun, error)` | `StartStream` followed by waiting for the run to finish, like `Call`. |
| `Build(ctx, versionNumber string, ActorBuildOptions) (Build, error)` | Build a version. |
| `DefaultBuild(ctx, waitForFinish *int64) (*BuildClient, error)` | Resolve the default build. |
| `ValidateInput(ctx, input any) (json.RawMessage, error)` | Validate input against the `latest` build's schema. |
Expand Down Expand Up @@ -153,7 +155,7 @@ fmt.Println(string(result)) // raw JSON validation result
| `WaitForFinish` | `*int64` | Max seconds to wait server-side for the run to finish (max 60). |
| `MaxItems` | `*int64` | Maximum dataset items to charge (pay-per-result Actors). |
| `MaxTotalChargeUsd` | `*float64` | Maximum total charge in USD (pay-per-event Actors). |
| `ContentType` | `*string` | Content type of the input body. Defaults to `application/json` for `Start`/`Call`, or `application/octet-stream` for `StartRaw`/`CallRaw`, when unset. |
| `ContentType` | `*string` | Content type of the input body. Defaults to `application/json` for `Start`/`Call`, or `application/octet-stream` for `StartRaw`/`CallRaw`/`StartStream`/`CallStream`, when unset. |
| `RestartOnError` | `*bool` | Restart the run if it fails. |
| `ForcePermissionLevel` | `*string` | Override the Actor's permission level for this run. Accepted values: `LIMITED_PERMISSIONS`, `FULL_PERMISSIONS`. |
| `Webhooks` | `[]any` | Ad-hoc webhooks to attach to this run. Each element is a map describing one webhook: `{"eventTypes": []string, "requestUrl": string, "payloadTemplate": string}` (same shape as a webhook definition; `eventTypes` are the `WebhookEventType` values listed in [webhooks.md](webhooks.md)). |
Expand Down Expand Up @@ -200,7 +202,7 @@ run, err := client.Actor("apify/hello-world").Call(ctx,

| Method | Description |
| --- | --- |
| `Versions().List(ctx)` / `Versions().Iterate()` / `Versions().Create(ctx, def)` | List/iterate/create versions. The endpoint returns every version in one response and takes no pagination parameters, so neither method takes options. |
| `Versions().List(ctx)` / `Versions().Iterate()` / `Versions().Create(ctx, def)` | List/iterate/create versions. `Create` and `Version(n).Update` use the long timeout tier, since a version can carry its source files. The endpoint returns every version in one response and takes no pagination parameters, so neither method takes options. |
| `Version(n).Get/Update/Delete(ctx)` | Manage a single version. |
| `Version(n).EnvVars().List(ctx)` / `.Iterate()` / `.Create(ctx, ActorEnvVar)` | List/iterate/create env vars. |
| `Version(n).EnvVar(name).Get/Update/Delete(ctx)` | Manage a single env var. |
Expand Down
Loading
Loading