---
title: "JSON API Server"
description: "EMILY.RPA JSON API Server 模組：建立可回覆 JSON 資料格式的 HTTP API 伺服器，會持續等待請求直到收到 DELETE 請求。"
source: https://docs.emily.tips/wap/http2json
---

# JSON API Server

建立一個可回覆 JSON 物件資料格式的 HTTP API 伺服器。請注意，由於這個模組是伺服器，除非請求方發送 DELETE 的請求或設定錯誤時停止伺服器並遇到錯誤，否則模組會保持等待請求。

![](https://docs.emily.tips/img/zh/wap-891.png)

## 參數

**`PORT`** - 伺服器連線埠號，預設為 8080。

**`Stop on Error`** - 當伺服器遇到錯誤或例外時自動停止。

## Low-Code 編輯器

### options 物件

在腳本中可以直接存取 options 內建物件。options 物件中的每個 key 為工作資料夾中的一個 TXT 檔案名稱（不包含副檔名），每個 value 為該檔案的文字內容，在腳本被執行時就會自動載入所有文檔，免去於腳本中自行讀取的麻煩：

```javascript
// 讀取工作資料夾中 price.txt 的值
let price = options['price']
console.log('price:', price)
```

### input 物件

input 物件代表正要處理的 HTTP 請求，其中包含 method, path, query 以及 body 等屬性，例如請求為 GET /orders?date=2023-08-26 時，會收到 input 物件如下：&#x20;

```javascript
// GET /orders?date=2023-08-26 請求的 input 物件：
{
  method: 'GET',
  path: '/orders',
  query: {
    date: '2023-08-26'
  },
  body: {
  }
}
```

請求方可以使用 POST, PUT 等 method 並在 body 中填入 JSON 資料格式，那麼 input.body 就會是請求方帶入的 JSON 資料解析後的結果。

### output 物件

output 物件代表想要回傳給請求方的 JSON 資料格式物件，可以填入符合 JSON 物件格式的內容：

```javascript
// 填寫 output 物件：
output.timestamp = moment().format('YYYY/MM/DD HH:mm:ss')
output.orders = [
  {
    orderId: 1234,
    items: ['coffee', 'milk']
  }
}
```

模組會自動將 output 內容完整填入 HTTP 回應後送出。

### api 物件

提供同步函式：api.files(), api.read(filename, encoding='utf8'), api.write(filename, text),  api.remove(filename)，[moment.js ](https://momentjs.com/docs/)與 [lodash](https://lodash.com/docs/4.17.15) 也都是內建函式庫，可以直接使用。另外提供非同步函式 api.run(uuid) 可以執行獨立技能，但請注意前一個 api.run 結束後才能呼叫新的 api.run 否則會回傳例外。

為了支援可存續的資料，api.datastore() 這個同步函式會回傳一個物件，所有在這個物件內的資料當伺服器停止時將自動寫入工作資料夾的 datastore.json，並在下次啟動時自動載入：

```javascript
// 取得 datastore 物件，伺服器會自動從工作資料夾中的 datastore.json 載入
let datastore = api.datastore()
datastore.reqNum += 1
```
