通過 SCF Component 輕鬆構建 REST API,再也不用熬夜加班了

當一個應用需要對第三方提供服務接口時,REST API 無疑是目前最主流的選擇。不過,如果自建 REST API,開發者需要購買虛擬機、配置環境等等,等一切都搞定,可能已經又是一個深夜。

而這些,都可以用 Serverless Framework 來解決。本教程將分享如何通過 Serverless SCF Component 、雲函數 SCF 及 API 網關組件,快速構建一個 REST API ,並實現 GET/PUT 操作。

通過 SCF Component 輕鬆構建 REST API,再也不用熬夜加班了

快速構建 REST API

  1. 安裝
  2. 配置
  3. 部署
  4. 測試
  5. 移除

1. 安裝

安裝 Serverless Framework

<code>$ npm install -g serverless/<code>

2. 配置

通過如下命令直接下載該例子,目錄結構如下:

<code>$ serverless create --template-url https://github.com/serverless/components/tree/master/templates/tencent-python-rest-api
.
├── code
| └── index.py
└── serverless.yml/<code>

查看 code/index.py 代碼,可以看到接口的傳參和返回邏輯:

<code># -*- coding: utf8 -*-

def teacher_go():
# todo: teacher_go action
return {
"result": "it is student_get action"
}

def student_go():
# todo: student_go action
return {
"result": "it is teacher_put action"
}

def student_come():
# todo: student_come action
return {
"result": "it is teacher_put action"
}

def main_handler(event, context):
print(str(event))
if event["pathParameters"]["user_type"] == "teacher":
if event["pathParameters"]["action"] == "go":
return teacher_go()
if event["pathParameters"]["user_type"] == "student":
if event["pathParameters"]["action"] == "go":
return student_go()
if event["pathParameters"]["action"] == "come":
return student_come()/<code>

3. 部署

通過 sls 命令進行部署,並可以添加 --debug 參數查看部署過程中的信息

如您的賬號未登陸或註冊騰訊雲,您可以直接通過微信掃描命令行中的二維碼進行授權登陸和註冊。

<code>$ serverless --debug

DEBUG ─ Resolving the template's static variables.
DEBUG ─ Collecting components from the template.
DEBUG ─ Downloading any NPM components found in the template.
DEBUG ─ Analyzing the template's components dependencies.
DEBUG ─ Creating the template's components graph.
DEBUG ─ Syncing template state.
DEBUG ─ Executing the template's components graph.
DEBUG ─ Compressing function myRestAPI file to /Users/dfounderliu/Desktop/restAPI/component/.serverless/myRestAPI.zip.
DEBUG ─ Compressed function myRestAPI file successful
DEBUG ─ Uploading service package to cos[sls-cloudfunction-ap-singapore-code]. sls-cloudfunction-default-myRestAPI-1574856533.zip
DEBUG ─ Uploaded package successful /Users/dfounderliu/Desktop/restAPI/component/.serverless/myRestAPI.zip
DEBUG ─ Creating function myRestAPI

DEBUG ─ Updating code...
DEBUG ─ Updating configure...
DEBUG ─ Created function myRestAPI successful
DEBUG ─ Setting tags for function myRestAPI
DEBUG ─ Creating trigger for function myRestAPI
DEBUG ─ Starting API-Gateway deployment with name myRestAPI.serverless in the ap-singapore region
DEBUG ─ Service with ID service-ibmk6o22 created.
DEBUG ─ API with id api-pjs3q3qi created.
DEBUG ─ Deploying service with id service-ibmk6o22.
DEBUG ─ Deployment successful for the api named myRestAPI.serverless in the ap-singapore region.
DEBUG ─ Deployed function myRestAPI successful

myRestAPI:
Name: myRestAPI
Runtime: Python3.6
Handler: index.main_handler
MemorySize: 128
Timeout: 20
Region: ap-singapore
Role: QCS_SCFExcuteRole
Description: My Serverless Function
APIGateway:
- serverless - http://service-ibmk6o22-1250000000.sg.apigw.tencentcs.com/release

10s › myRestAPI › done/<code>

4. 測試

通過如下命令測試 REST API 的返回情況:

注:如 Windows 系統中未安裝 curl,也可以直接通過瀏覽器打開對應鏈接查看返回情況

<code>$ curl -XGET http://service-9t28e0tg-1250000000.sg.apigw.tencentcs.com/release/users/teacher/go

{"result": "it is student_get action"}
$ curl -PUT http://service-9t28e0tg-1250000000.sg.apigw.tencentcs.com/release/users/student/go

{"result": "it is teacher_put action"}/<code>

5. 移除

可以通過以下命令移除 REST API 應用

<code>$ sls remove --debug 


DEBUG ─ Flushing template state and removing all components.
DEBUG ─ Removing any previously deployed API. api-37gk3l8q
DEBUG ─ Removing any previously deployed service. service-9t28e0tg
DEBUG ─ Removing function
DEBUG ─ Request id
DEBUG ─ Removed function myRestAPI successful

7s » myRestAPI » done/<code>

賬號配置(可選)

當前默認支持 CLI 掃描二維碼登錄,如您希望配置持久的環境變量/秘鑰信息,也可以本地創建 .env 文件

<code>$ touch .env # 騰訊雲的配置信息/<code>

在 .env 文件中配置騰訊雲的 SecretId 和 SecretKey 信息並保存

如果沒有騰訊雲賬號,可以在此註冊新賬號。

如果已有騰訊雲賬號,可以在 API 密鑰管理中獲取 SecretId 和SecretKey.

<code># .env
TENCENT_SECRET_ID=123
TENCENT_SECRET_KEY=123/<code>

查看:完整倉庫模板

目前 REST API 模板主要展示了 GET/PUT 操作,後續騰訊雲 Serverless Framework 也將支持對 Serverless DB 的連接,可以完整實現 CRUD 操作,並支持資源的彈性擴縮容。您可以通過該模板快速開發業務 REST API、擴展代碼,探索更豐富的場景。


分享到:


相關文章: