> This page is for SDK, version Current (default).
> For other versions, use one of these documentation indexes:
> - Current (default): https://buildwithfern.com/learn/sdks/current/llms.txt
> - Legacy: https://buildwithfern.com/learn/sdks/legacy/llms.txt

> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt.

# 服务器 URL 模板化

> 在 Fern SDK 中配置服务器 URL 模板化，支持使用区域和环境等变量的动态基础 URL。

服务器 URL 模板化让你可以定义带有变量占位符的基础 URL（例如 `{region}`、`{environment}`），SDK 用户可以在运行时自定义这些变量。这对于部署在多个区域、环境或自定义域名的 API 非常有用。

> **Note**
>
> URL 模板化目前仅支持 Python 和 Java SDK 生成。

## 生成的 SDK 行为

Fern 生成一个环境模块，它暴露了每个命名服务器的默认 URL。SDK 用户可以选择预定义的环境或传递自定义 URL 字符串。

#### Python

生成的 SDK 暴露了一个 `Environment` 类：

**`environment.py`**

```python title="environment.py"
class MyApiEnvironment:
    REGIONAL_API_SERVER = {
        "base": "https://api.example.com/v1",
        "auth": "https://auth.example.com",
    }
```

SDK 用户可以在构造客户端时覆盖基础 URL：

```python
from my_api import MyApiClient

# 使用默认环境
# → https://api.example.com/v1
client = MyApiClient()

# 通过 URL 变量指定特定区域和环境
# → https://api.eu-west-1.staging.example.com/v1
client = MyApiClient(
    region="eu-west-1",
    environment="staging",
)

# 或者提供自定义基础 URL
# → https://api.us-west-2.staging.example.com/v1
client = MyApiClient(
    base_url="https://api.us-west-2.staging.example.com/v1",
)
```

#### Java

生成的 SDK 暴露了一个 `Environment` 类：

**`Environment.java`**

```java title="Environment.java"
public final class Environment {
    public static final Environment REGIONAL_API_SERVER =
        new Environment(
            "https://api.example.com/v1",
            "https://auth.example.com"
        );
    public static Builder custom() { return new Builder(); }
}
```

生成的 SDK 暴露了一个环境枚举和构建器方法：

```java
import com.example.api.MyApiClient;

// 使用默认环境
// → https://api.example.com/v1
MyApiClient client = MyApiClient.builder().build();

// 通过 URL 变量指定特定区域和环境
// → https://api.eu-west-1.staging.example.com/v1
MyApiClient client = MyApiClient.builder()
    .region("eu-west-1")
    .serverUrlEnvironment("staging")
    .build();

// 或者提供自定义基础 URL
// → https://api.us-west-2.staging.example.com/v1
MyApiClient client = MyApiClient.builder()
    .url("https://api.us-west-2.staging.example.com/v1")
    .build();
```

## 设置服务器 URL 模板化

在你的 API 定义中定义 URL 模板变量，并为不自定义变量的 SDK 用户提供静态回退 URL：

**`openapi.yml`**

```yaml title="openapi.yml"
servers:
  - url: https://api.{region}.{environment}.example.com/v1
    x-fern-server-name: Default
    x-fern-default-url: https://api.example.com/v1
    variables:
      region:
        default: us-east-1
        enum: [us-east-1, us-west-2, eu-west-1]
      environment:
        default: prod
        enum: [prod, staging, dev]
```

有关完整配置详情，请参阅 [OpenAPI 中的服务器名称和 URL 模板化](/learn/zh/api-definitions/openapi/extensions/server-names-and-url-templating)。