
ASP.NET Web API快速入門介紹
我們也可以通過修改 prompt,要求 ChatGPT 來添加或刪除一些字段。
如果對這些字段感到滿意,就可以要求 ChatGPT 生成 JSON
{
"products": [
{
"id": "12345",
"category": "Smartphones",
"brand": "Apple",
"model": "iPhone 13 Pro",
"features": {
"display_size": "6.1 inches",
"camera_resolution": "12 MP",
"battery_life": "22 hours",
"storage_capacity": "256 GB",
"connectivity": "5G"
},
"price": 1099
},
{
"id": "67890",
"category": "Laptops",
"brand": "Dell",
"model": "XPS 13",
"features": {
"display_size": "13.4 inches",
"processor": "Intel Core i7",
"memory": "16 GB",
"storage_capacity": "512 GB SSD",
"graphics": "Intel Iris Xe"
},
"price": 1399
},
{
"id": "13579",
"category": "Cameras",
"brand": "Sony",
"model": "Alpha a7 III",
"features": {
"sensor_resolution": "24.2 MP",
"image_stabilization": "5-axis",
"video_resolution": "4K",
"viewfinder": "Electronic",
"connectivity": "Wi-Fi, NFC, Bluetooth"
},
"price": 1999
},
{
"id": "24680",
"category": "Gaming Devices",
"brand": "Nintendo",
"model": "Switch OLED",
"features": {
"display_size": "7 inches OLED",
"resolution": "720p",
"battery_life": "Up to 9 hours",
"storage_capacity": "64 GB",
"connectivity": "Wi-Fi, Bluetooth"
},
"price": 349
},
{
"id": "97531",
"category": "Home Appliances",
"brand": "Samsung",
"model": "WF45K6500AV",
"features": {
"load_capacity": "4.5 cu. ft.",
"wash_cycles": "14",
"energy_star_certified": true,
"steam_wash": true,
"smart_connectivity": "Wi-Fi"
},
"price": 1099
}
]
}
有了樣例數據之后,可以使用 json-server 創建 API 路由。首先在項目的根目錄中創建一個 db.json 文件,然后從 ChatGPT 復制粘貼樣例數據到文件中。
接下來,安裝 json-server-npm 作為 dev 依賴項:
npm i json-server -D
最后,添加一個 npm 腳本,使用樣例數據運行 json-server:
"serve-json": "json-server --watch db.json --port 4000"
運行 npm run serve-json 將在 http://localhost:4000 上創建一個服務,并且提供了所有必要的路由。以下將具體介紹如何使用這些路由。
GET /products
GET /products/:id
POST /products
PUT /products/:id
PATCH /products/:id
DELETE /products/:id
將字段名稱作為查詢參數傳遞,可以訪問深層屬性。
GET /products?category=laptops&brand=Dell
GET /products?id=12345
GET /comments?features.resolution=720p
使用 _page 和可選的 _limit 對返回的數據進行分頁。(我們的數據只有一頁)。
GET /products?_page=7
GET /products?_page=7&_limit=20
添加排序 _sort 和順序 _order(默認情況下按升序)。
GET /products?_sort=price&_order=desc
使用 _gte 或 _lte 獲取某個范圍內的數據
GET /products?price_gte=1000&price_lte=2000
使用 _ne 排除一個值
GET /products?id_ne=12345
使用 _like 過濾
GET /products?model_like=iPhone
使用 q 進行檢索
GET /products?q=laptop
使用 ChatGPT 和 json-server,可以幫助前端開發人員生成 mock 數據,并通過 RESTful API 輕松提供數據。ChatGPT 讓生成數據集變得輕而易舉,使用 json-server 可以零編碼創建 fake RESTful API。它們為快速模擬 API 創建提供了簡單而有效的解決方案,前端開發人員可以專注于快速高效地構建原型,而無需擔心數據生成和 API 實現。
本文章轉載微信公眾號@KooFE前端團隊