作者:Nicolas Fränkel翻译:Sylviahttps://blog.frankel.ch/poor-man-api/在 API 日渐风行的年代,越来越多的非技术人员也心愿能从 API 的应用中获利,而创立一套成熟的 API 计划须要工夫老本和金钱两方面的资源加持。在这个过程中,你须要思考模型、设计、REST 准则等,而不仅仅是编写一行代码。
如何打造一个具备高性价比且能继续迭代的产品,成为越来越多技术团队的指标。本文将展现如何在不编写任何代码的状况下,简略实现一个 API 实际。
计划初试该解决方案次要应用的是 PostgreSQL 数据库,PostgreSQL 是一个开源 SQL 数据库。同时咱们没有编写 REST API,而是应用了 PostgREST 组件。
PostgREST 是一个独立的 Web 服务器,它能够将 PostgreSQL 数据库间接转换为 RESTful API。如果你想理解 PostgREST 的应用办法,能够参考入门指南文档,内容十分全面且开箱即用。
接下来,咱们将它利用到一个简略的示例中。
具体步骤以下过程你能够在 GitHub 上找到残缺源代码。下方展现了一个通过 CRUD API 公开的 product 表。
因为我没有找到任何现成的 Docker 镜像,所以我独自创立了一份新的 Dockerfile。其中次要波及依赖项的装置和参数化数据生成。
Dockerfile
FROM debian:bookworm-slim ARG POSTGREST_VERSION=v10.1.1 ARG POSTGREST_FILE=postgrest-$POSTGREST_VERSION-linux-static-x64.tar.xz RUN mkdir postgrestWORKDIR postgrestADD https://github.com/PostgREST/postgrest/releases/download/$POSTGREST_VERSION/$POSTGREST_FILE \ . RUN apt-get update && \ apt-get install -y libpq-dev xz-utils && \ tar xvf $POSTGREST_FILE && \ rm $POSTGREST_FILE之后,Docker 镜像在 /postgrest 文件夹中会蕴含一个名为 postgrest 的可执行文件。这里能够通过 Docker Compose 来部署:
docker-compose.yml
version: "3"services: postgrest: build: ./postgrest volumes: - ./postgrest/product.conf:/etc/product.conf:ro ports: - "3000:3000" entrypoint: ["/postgrest/postgrest"] command: ["/etc/product.conf"] depends_on: - postgres postgres: image: postgres:15-alpine environment: POSTGRES_PASSWORD: "root" volumes: - ./postgres:/docker-entrypoint-initdb.d:ro接下来能够执行以下命令,查问前文提到的 product 表:
curl localhost:3000/product失去如下后果反馈:
[{"id":1,"name":"Stickers pack","description":"A pack of rad stickers to display on your laptop or wherever you feel like. Show your love for Apache APISIX","price":0.49,"hero":false}, {"id":2,"name":"Lapel pin","description":"With this \"Powered by Apache APISIX\" lapel pin, support your favorite API Gateway and let everybody know about it.","price":1.49,"hero":false}, {"id":3,"name":"Tee-Shirt","description":"The classic geek product! At a conference, at home, at work, this tee-shirt will be your best friend.","price":9.99,"hero":true}]计划优化只管上文提到的这套解决方案无效,但仍存在很大的改良空间。比方数据库用户不能更改数据、实际操作中每个人都能够拜访相干数据等。这对于与产品相干的数据来说,可能不是一个大问题,但如果是医疗数据呢?
PostgREST 的官网应用文档中提到了这一点,并明确提出:倡议用户应用反向代理。
提到反向代理,就不得不将眼光转向到 API 网关行列。与 NGINX 不同,这里我选取了开源畛域十分沉闷的 API 网关产品 — Apache APISIX。APISIX 是一个动静、实时、高性能的 API 网关,提供了负载平衡、动静上游、灰度公布、精细化路由、限流限速、服务降级、服务熔断、身份认证、可观测性等数百项性能。
...