飲料訂購APP|SheetDB 存取訂單資料
Published in
5 min readMay 2, 2021
SheetDB API GET/POST 存取資料
本篇為 SheetDB POST/GET 存取訂單資料
🌟 本篇技術項目
・SheetDB api POST 新增 Google Sheet 資料
・SheetDB api GET 讀取 Google Sheet 資料
取得 SheetDB API 網址
規劃出存取資料格式(Keys),並將網址貼入SheetDB,Create 創建 API,即得到 API 網址。
POST 新增資料:
在 SheetDB 文件中表示上傳的物件需存放於data
範圍裡,keys 需與 google sheet 裡的資料格式名稱相同。
設定URLRequest
新增資料 httpMethod = “POST”
value 為 “application/json”
headerField 為 “Content-Type”
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
對欲上傳資料進行編碼後,帶入 httpBody
if let data = try? JSONEncoder().encode(postOrder){
urlRequest.httpBody = data
檢查上傳的 JSON 印出字串,如成功上傳將得到該字串“created”:1
URLSession.shared.dataTask(with: urlRequest) { data, response, error in
//檢查上傳的JSON印出字串
if let data = data,
let content = String(data: data, encoding: .utf8){
print(content)
GET 讀取資料:
設定URLRequest
讀取資料 httpMethod = “GET”
value 為 “application/json”
headerField 為 “Content-Type”
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "GET"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
POSTMAN 抓取資料結構為[[String:String]]
,因此使用[[String:String]]
字典結構 來解析JSON
let searchResponse = try decoder.decode([[String:String]].self, from: data)
GitHub