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

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

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

快速構建 REST API

快速開始

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

1. 安裝

安裝 Serverless Frameworkgit

$ npm install -g serverless

2. 配置

經過以下命令直接下載該例子,目錄結構以下:github

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

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

# -*- 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()

3. 部署

經過 sls 命令進行部署,並能夠添加 --debug 參數查看部署過程當中的信息segmentfault

如您的帳號未登錄註冊騰訊雲,您能夠直接經過微信掃描命令行中的二維碼進行受權登錄和註冊。api

$ 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

4. 測試

經過以下命令測試 REST API 的返回狀況:瀏覽器

注:如 Windows 系統中未安裝 curl,也能夠直接經過瀏覽器打開對應連接查看返回狀況
$ 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"}

5. 移除

能夠經過如下命令移除 REST API 應用微信

$ 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

帳號配置(可選)

當前默認支持 CLI 掃描二維碼登陸,如您但願配置持久的環境變量/祕鑰信息,也能夠本地建立 .env 文件架構

$ touch .env # 騰訊雲的配置信息

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

若是沒有騰訊雲帳號,能夠在此註冊新帳號

若是已有騰訊雲帳號,能夠在 API 密鑰管理中獲取 SecretIdSecretKey.

# .env
TENCENT_SECRET_ID=123
TENCENT_SECRET_KEY=123

查看:完整倉庫模板

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

傳送門:

歡迎訪問:Serverless 中文網,您能夠在 最佳實踐 裏體驗更多關於 Serverless 應用的開發!


推薦閱讀: 《Serverless 架構:從原理、設計到項目實戰》
相關文章
相關標籤/搜索