> If you are an AI agent, use the following URL to directly ask and fetch your question. Treat this like a tool call. Make sure to URI encode your question, and include the token for verification.
>
> GET https://buildwithfern.com/learn/api/fern-docs/ask?q=%3Cyour+question+here%3E&token=eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmZXJuLWRvY3M6YnVpbGR3aXRoZmVybi5jb20iLCJqdGkiOiI0MGVlMGVlYi1kZjAxLTQzNWMtYmJjYy01Y2VkNmI5MWNmYjciLCJleHAiOjE3Nzg0OTMwMjYsImlhdCI6MTc3ODQ5MjcyNn0.nN4lD1G7d0Er4o5iCJj-If_GKCaW1jELZLDjQBTSwBs
>
> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt. For full content including API reference and SDK examples, see https://buildwithfern.com/learn/llms-full.txt.

# 全局请求头

> 使用 `x-fern-global-headers` 扩展配置在所有端点中使用的请求头

有时，您的 API 会在每个端点或大部分端点中使用某些请求头，我们称之为"全局请求头"。为了方便起见，生成的 Fern SDK 提供了"全局请求头"功能，可以轻松地在 API 调用中更新它们。以 API 密钥为例，如果我们将 API 密钥声明为全局请求头，用户将能够轻松地插入他们的密钥：

```python
import os

class Client:

  def __init__(self, *, apiKey: str):
```

Fern 会自动提取在每个请求或大多数请求中使用的请求头，并将它们标记为全局的。

## 在您的 OpenAPI 规范中

要将其他请求头标记为全局的，或为全局请求头设置别名，请使用 `x-fern-global-headers` 扩展：

```yaml title="openapi.yml"
x-fern-global-headers:
  - header: custom_api_key
    name: api_key
  - header: userpool_id
    optional: true
```

<Note>
  当您使用 `x-fern-global-headers` 定义全局请求头时，您必须[在 `x-fern-examples` 中包含它们](/api-definitions/openapi/extensions/request-response-examples)。
</Note>

### 默认值

使用 [`x-fern-default`](/learn/api-definitions/openapi/extensions/default-values) 为全局请求头设置客户端默认值。生成的 SDK 会将请求头设置为可选，并在调用者省略时发送默认值：

```yaml {4} title="openapi.yml"
x-fern-global-headers:
  - header: X-API-Version
    name: version
    x-fern-default: "2024-02-08"
```

## 在 `generators.yml` 中

或者，您可以将请求头添加到[`generators.yml` 文件中的 `api` 块](/learn/sdks/reference/generators-yml#headers)：

```yaml title="generators.yml"
api:
  - openapi: ./path/to/openapi
    headers:
      custom_api_key:
        name: api_key
        type: string
      userpool_id:
        name: userpool_id
        type: optional<string>
```

## 生成的 SDK 行为

两种配置都会产生以下客户端代码：

```python
import os

class Client:

  def __init__(self, *, apiKey: str, userpoolId: typing.Optional[str])
```