本教程将分享如何通过 Serverless SCF Component 、云函数 SCF 及 API 网关组件,快速构建一个 REST API 并实现 GET/PUT 操作。

当一个应用需要对第三方提供服务接口时,REST API 无疑是目前最主流的选择。不过,如果自建 REST API,开发者需要购买虚拟机、配置环境等等,等一切都搞定,可能已经又是一个深夜。

而这些,都可以用 Serverless Framework 来解决。本教程将分享如何通过 Serverless SCF Component 、云函数 SCF 及 API 网关组件,快速构建一个 REST API ,并实现 GET/PUT 操作。

快速构建 REST API

快速开始

  1. 安装
  2. 配置
  3. 部署
  4. 测试
  5. 移除

1. 安装

安装 Serverless Framework

$ npm install -g serverless

2. 配置

通过如下命令直接下载该例子,目录结构如下:

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

查看 code/index.py 代码,可以看到接口的传参和返回逻辑:

# -*- 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 参数查看部署过程中的信息

如您的账号未登陆注册腾讯云,您可以直接通过微信扫描命令行中的二维码进行授权登陆和注册。

$ 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 应用的开发!

通过 SCF Component 轻松构建 REST API,再也不用熬夜加班了的更多相关文章

  1. springboot集成swagger2构建RESTful API文档

    在开发过程中,有时候我们需要不停的测试接口,自测,或者交由测试测试接口,我们需要构建一个文档,都是单独写,太麻烦了,现在使用springboot集成swagger2来构建RESTful API文档,可 ...

  2. 使用ASP.NET Core 3.x 构建 RESTful API - 2. 什么是RESTful API

    1. 使用ASP.NET Core 3.x 构建 RESTful API - 1.准备工作 什么是REST REST一词最早是在2000年,由Roy Fielding在他的博士论文<Archit ...

  3. 使用ASP.NET Core构建RESTful API的技术指南

    译者荐语:利用周末的时间,本人拜读了长沙.NET技术社区翻译的技术标准<微软RESTFul API指南>,打算按照步骤写一个完整的教程,后来无意中看到了这篇文章,与我要写的主题有不少相似之 ...

  4. 腾讯大牛半年心血高级编程PDF,帮你轻松构建企业级Web应用

    毫无疑问,Java 是这些年来最流行的编程语言之一.它无处不在一计算机. 手机.网站以及各种嵌入式设备中都存在着大量的Java 应用程序,而其中应用最为广泛的应该就是Java EE Web应用程序(以 ...

  5. 在 .NET Core 中构建 REST API

    翻译自 Camilo Reyes 2020年8月26日的文章 <Build a REST API in .NET Core> [1] REST API 可以使用简单的动词(如 POST.P ...

  6. Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档

    前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...

  7. Spring MVC中使用 Swagger2 构建Restful API

    1.Spring MVC配置文件中的配置 [java] view plain copy <!-- 设置使用注解的类所在的jar包,只加载controller类 --> <contex ...

  8. php 使用 restler 框架构建 restfull api

    php 使用 restler 框架构建 restfull api restler 轻量级,小巧,构建restfull api非常方便! 官网:http://restler3.luracast.com/ ...

  9. spring boot / cloud (三) 集成springfox-swagger2构建在线API文档

    spring boot / cloud (三) 集成springfox-swagger2构建在线API文档 前言 不能同步更新API文档会有什么问题? 理想情况下,为所开发的服务编写接口文档,能提高与 ...

随机推荐

  1. MyISAM与InnoDB的索引实现区别

    一 MyISAM索引实现 1. 主键索引 MyISAM引擎使用B+树作为索引结果,叶节点的data域存放的是数据记录的地址.下图为MyISAM表的主索引,Col1为主键. 2. 辅助索引 在MyISA ...

  2. 大数据(5)---分布式任务资源调度Yarn

    前面也说到过的Yarn是hadoop体系中的资源调度平台.所以在整个hadoop的包里面自然也是有它的.这里我们就简单介绍下,并配置搭建yarn集群. 首先来说Yarn中有两大核心角色Resource ...

  3. vue入门,vue指令,vue组件,vue模板

    vue 使用虚拟dom操作减少真实dom操作 提高页面的渲染效率 虚拟dom的本质就是内存中的一个对象,该对象和dom结构相互对应 将开发者经历从dom中释放出来,转移到数据的操作 开发者不需要关注页 ...

  4. 【一起学源码-微服务】Ribbon 源码三:Ribbon与Eureka整合原理分析

    前言 前情回顾 上一篇讲了Ribbon的初始化过程,从LoadBalancerAutoConfiguration 到RibbonAutoConfiguration 再到RibbonClientConf ...

  5. 使用SqlDependency实时监听SQL server数据库变化并执行事件

    sql server设置:ALTER DATABASE <DatabaseName> SET ENABLE_BROKER;语句让相应的数据库启用监听服务,以便支持SqlDependency ...

  6. 理解TCP/IP协议栈之HTTP2.0

    1 前言 前面写了10多篇关于Redis底层实现.工程架构.实际应用的文章,感兴趣的读者可以进行阅读,如有问题欢迎交流: 1.Redis面试热点之底层实现篇-12.Redis面试热点之底层实现篇-23 ...

  7. 【转】常见Java面试题 – 第一部分:非可变性(Immutability)和对象引用(Object reference)

    ImportNew注: 本文是ImportNew编译整理的Java面试题系列文章之一.请看此系列相关面试题.你可以从这里查看全部的Java面试系列. 一些比较核心的Java问题经常会用来考验面试者的J ...

  8. String字符串,输入一串字符判断其中数字,字母,其他的字符的个数

    public class StringClassTest { public static void main(String[] args) { //遍历字符串 String str = "H ...

  9. python的list()函数

    list()函数将其它序列转换为 列表 (就是js的数组). 该函数不会改变   其它序列 效果图一: 代码一: # 定义一个元组序列 tuple_one = (123,','abc') print( ...

  10. FFT 入门

    推荐博客 :https://oi.men.ci/fft-notes/ 卷积的理解 : https://www.zhihu.com/question/22298352?rf=21686447 题目链接 ...