> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.orderupb2b.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.orderupb2b.com/_mcp/server.

# 建立規格

POST https://api.example.com/v1/skus
Content-Type: application/json

建立單一規格。outerSysCode 為必填，省略回傳 400 outerSysCode is required to create a SKU；productId 也是必填且必須指向既有商品，省略或帶入非正整數回傳 400 productId is required to create a SKU。庫存不能在這裡設定——新建規格的在庫數固定為 0，之後要用庫存的專屬端點寫入（見「庫存」）。未帶 id 且 outerSysCode 未對應到同一商品底下的既有規格時新增；outerSysCode 已存在於同一商品底下時改為更新該筆（去重比對限定在同一個 productId 之內，不同商品下的相同代碼不會互相匹配），重送同一份資料不會產生重複規格。

Reference: https://docs.orderupb2b.com/api-reference/skus/create-sku

## Authentication

- `X-Signature` header (required) — 每個 /v1 請求都必須帶 X-Client-Id、X-Timestamp、X-Nonce 與 X-Signature 四個標頭。X-Signature 是以 client secret 對 canonical string 做 HMAC-SHA256 後的 Base64。canonical string 的組成、可複製的簽章範例與 401 排查步驟，請參閱「驗證與簽章」。

## Request

### Body (application/json)

This endpoint expects an object.

- `id` (long, optional, nullable) — 規格序號。帶 id 時一律視為更新該筆規格，不會再比對 outerSysCode；省略時改依 productId 與 outerSysCode 判斷新增或更新。PUT /v1/skus/\{id} 會忽略這裡的值，一律以路徑上的 id 為準。
- `productId` (long, optional, nullable) — 對應的商品序號，必須指向既有商品。新增時為必填，省略或帶入非正整數回傳 400 productId is required to create a SKU；更新時省略會保留規格目前所屬的商品，帶新值則會把規格改到另一個商品底下。outerSysCode 的去重比對也是以這個欄位限定範圍，同一組 outerSysCode 換一個 productId 視為完全不同的比對對象。
- `outerSysCode` (string, optional, nullable) — ERP 端的規格代碼，用來在同一個 productId 底下與既有規格比對、去重，不同商品下的相同代碼不會互相匹配。新增時為必填，省略回傳 400 outerSysCode is required to create a SKU；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 outer_sys_code_too_long。
- `name` (string, optional, nullable) — 名稱。新增時省略視為空字串；更新時省略保留現有值。長度上限 100 字元，超過回傳 400 name_too_long。
- `barcode` (string, optional, nullable) — 條碼。查詢時是精確比對，與 outerSysCode、name 的子字串比對不同，詳見 listSkus 端點說明。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 barcode_too_long。
- `warehouse` (string, optional, nullable) — 倉別。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 warehouse_too_long。
- `unit` (string, optional, nullable) — 商品單位。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 unit_too_long。
- `spec` (string, optional, nullable) — 規格內容（例如「12入」「500g」）。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 spec_too_long。
- `price` (double, optional, nullable) — 價格。新增時省略視為 0；更新時省略保留現有值。
- `sellPrice` (double, optional, nullable) — 賣價。新增時省略視為 0；更新時省略保留現有值。
- `quantityPrecision` (integer, optional, nullable) — 數量精度（0 為整數，1 至 4 為小數位數）。新增時省略視為 0；更新時省略保留現有值。

## Response

### 200

OK

- `id` (long, optional) — 新增或更新成功後，該筆資料的 id。

### 201

Created

- `id` (long, optional) — 新增或更新成功後，該筆資料的 id。

## Errors

### 401 Unauthorized Error

Unauthorized

- `error` (string, optional, nullable) — 錯誤代碼，固定為 snake_case 字串，依代碼判斷失敗原因。

### 403 Forbidden Error

Forbidden

- `error` (string, optional, nullable) — 錯誤代碼，固定為 snake_case 字串，依代碼判斷失敗原因。

### 500 Internal Server Error

Internal Server Error

- `code` (string, optional, nullable) — 錯誤代碼字串。
- `message` (string, optional, nullable) — 對應的錯誤說明文字。

## Examples

### Example 1

**Request**

```json
{}
```

**Response**

```json
{
  "id": 1
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/skus"

payload = {}
headers = {
    "X-Signature": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.example.com/v1/skus';
const options = {
  method: 'POST',
  headers: {'X-Signature': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.example.com/v1/skus"

	payload := strings.NewReader("{}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("X-Signature", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.example.com/v1/skus")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["X-Signature"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.example.com/v1/skus")
  .header("X-Signature", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/v1/skus', [
  'body' => '{}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Signature' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/v1/skus");
var request = new RestRequest(Method.POST);
request.AddHeader("X-Signature", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "X-Signature": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/v1/skus")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### Example 2

**Request**

```json
{}
```

**Response**

```json
{
  "id": 1
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/skus"

payload = {}
headers = {
    "X-Signature": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.example.com/v1/skus';
const options = {
  method: 'POST',
  headers: {'X-Signature': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.example.com/v1/skus"

	payload := strings.NewReader("{}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("X-Signature", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.example.com/v1/skus")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["X-Signature"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.example.com/v1/skus")
  .header("X-Signature", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/v1/skus', [
  'body' => '{}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Signature' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/v1/skus");
var request = new RestRequest(Method.POST);
request.AddHeader("X-Signature", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "X-Signature": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/v1/skus")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```