> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/vercel/workflow/llms.txt
> Use this file to discover all available pages before exploring further.

# fetch

> Make HTTP requests from within workflows

A hoisted `fetch()` function that is executed as a step function, allowing you to make HTTP requests from within workflow functions.

This is the standard [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) wrapped as a step, providing durability and automatic retries for HTTP requests.

## Signature

```typescript theme={null}
function fetch(
  input: RequestInfo | URL,
  init?: RequestInit
): Promise<Response>
```

## Parameters

<ParamField path="input" type="RequestInfo | URL" required>
  The URL to fetch. Can be a string, URL object, or Request object.
</ParamField>

<ParamField path="init" type="RequestInit" optional>
  Request options.

  <Expandable title="properties">
    <ParamField path="method" type="string" optional>
      HTTP method (GET, POST, PUT, DELETE, etc.). Defaults to GET.
    </ParamField>

    <ParamField path="headers" type="HeadersInit" optional>
      Request headers as an object, Headers instance, or array of tuples.
    </ParamField>

    <ParamField path="body" type="BodyInit" optional>
      Request body. Can be a string, FormData, Blob, ArrayBuffer, or URLSearchParams.
    </ParamField>

    <ParamField path="signal" type="AbortSignal" optional>
      AbortSignal to cancel the request.
    </ParamField>

    <ParamField path="cache" type="RequestCache" optional>
      Cache mode (default, no-store, reload, no-cache, force-cache, only-if-cached).
    </ParamField>

    <ParamField path="credentials" type="RequestCredentials" optional>
      Credentials mode (omit, same-origin, include).
    </ParamField>

    <ParamField path="mode" type="RequestMode" optional>
      Request mode (cors, no-cors, same-origin).
    </ParamField>

    <ParamField path="redirect" type="RequestRedirect" optional>
      Redirect handling (follow, error, manual).
    </ParamField>

    <ParamField path="referrer" type="string" optional>
      Referrer URL.
    </ParamField>

    <ParamField path="integrity" type="string" optional>
      Subresource integrity value.
    </ParamField>
  </Expandable>
</ParamField>

## Returns

<ResponseField name="Response" type="Promise<Response>">
  A Promise that resolves to a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object.

  <Expandable title="properties">
    <ResponseField name="status" type="number">
      HTTP status code (200, 404, 500, etc.).
    </ResponseField>

    <ResponseField name="statusText" type="string">
      HTTP status message.
    </ResponseField>

    <ResponseField name="ok" type="boolean">
      True if status is in the range 200-299.
    </ResponseField>

    <ResponseField name="headers" type="Headers">
      Response headers.
    </ResponseField>

    <ResponseField name="json" type="() => Promise<any>">
      Parse response body as JSON.
    </ResponseField>

    <ResponseField name="text" type="() => Promise<string>">
      Get response body as text.
    </ResponseField>

    <ResponseField name="blob" type="() => Promise<Blob>">
      Get response body as a Blob.
    </ResponseField>

    <ResponseField name="arrayBuffer" type="() => Promise<ArrayBuffer>">
      Get response body as an ArrayBuffer.
    </ResponseField>

    <ResponseField name="formData" type="() => Promise<FormData>">
      Parse response body as FormData.
    </ResponseField>
  </Expandable>
</ResponseField>

## Usage

### Basic GET Request

Fetch data from an API:

```typescript theme={null}
import { fetch } from 'workflow';

export async function workflowWithFetch() {
  "use workflow";

  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  
  console.log('Fetched data:', data);
}
```

### POST Request with JSON

Send JSON data:

```typescript theme={null}
import { fetch } from 'workflow';

export async function createUser(userData: any) {
  "use workflow";

  const response = await fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(userData),
  });

  if (!response.ok) {
    throw new Error(`Failed to create user: ${response.statusText}`);
  }

  const user = await response.json();
  return user;
}
```

### Custom Headers

Include authentication headers:

```typescript theme={null}
import { fetch } from 'workflow';

export async function authenticatedRequest(apiKey: string) {
  "use workflow";

  const response = await fetch('https://api.example.com/protected', {
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'X-Custom-Header': 'value',
    },
  });

  return await response.json();
}
```

### Handle Different Status Codes

Check response status:

```typescript theme={null}
import { fetch } from 'workflow';

export async function handleStatusCodes() {
  "use workflow";

  const response = await fetch('https://api.example.com/data');

  if (response.status === 404) {
    console.log('Resource not found');
    return null;
  }

  if (response.status === 429) {
    console.log('Rate limited');
    throw new Error('Rate limit exceeded');
  }

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  return await response.json();
}
```

### PUT Request

Update a resource:

```typescript theme={null}
import { fetch } from 'workflow';

export async function updateResource(id: string, updates: any) {
  "use workflow";

  const response = await fetch(`https://api.example.com/items/${id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(updates),
  });

  return await response.json();
}
```

### DELETE Request

Delete a resource:

```typescript theme={null}
import { fetch } from 'workflow';

export async function deleteResource(id: string) {
  "use workflow";

  const response = await fetch(`https://api.example.com/items/${id}`, {
    method: 'DELETE',
  });

  if (response.status === 204) {
    console.log('Resource deleted successfully');
    return true;
  }

  return false;
}
```

### Form Data Upload

Submit form data:

```typescript theme={null}
import { fetch } from 'workflow';

export async function uploadFile(file: Blob, filename: string) {
  "use workflow";

  const formData = new FormData();
  formData.append('file', file, filename);
  formData.append('description', 'My file');

  const response = await fetch('https://api.example.com/upload', {
    method: 'POST',
    body: formData,
  });

  return await response.json();
}
```

### Query Parameters

Construct URLs with query parameters:

```typescript theme={null}
import { fetch } from 'workflow';

export async function searchItems(query: string, limit: number) {
  "use workflow";

  const params = new URLSearchParams({
    q: query,
    limit: String(limit),
  });

  const response = await fetch(`https://api.example.com/search?${params}`);
  return await response.json();
}
```

### Response Headers

Access response headers:

```typescript theme={null}
import { fetch } from 'workflow';

export async function checkHeaders() {
  "use workflow";

  const response = await fetch('https://api.example.com/data');
  
  const contentType = response.headers.get('Content-Type');
  const rateLimit = response.headers.get('X-RateLimit-Remaining');
  
  console.log('Content-Type:', contentType);
  console.log('Rate limit remaining:', rateLimit);
  
  return await response.json();
}
```

## Important Notes

* **Must import from 'workflow'**: Do not use `globalThis.fetch` inside workflow functions. Always import and use `fetch` from the `workflow` package.
* **Executed as a step**: Each fetch call is automatically wrapped as a step, providing durability and retry capabilities.
* **Automatic retries**: Failed requests are automatically retried according to your step retry configuration.
* **Can only be used in workflows**: The `fetch` function from `workflow` can only be called inside workflow functions (with `"use workflow"`)
* **Standard Fetch API**: Follows the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) specification

## Related

* [RetryableError](/api-reference/workflow/retryable-error) - Control fetch retry behavior
* [FatalError](/api-reference/workflow/fatal-error) - Mark fetch errors as non-retryable


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.