ホームページ  >  記事  >  ウェブフロントエンド  >  [Roast: Day - AI を使用せずに API サーバーを自動作成する]

[Roast: Day - AI を使用せずに API サーバーを自動作成する]

WBOY
WBOYオリジナル
2024-07-31 20:47:02400ブラウズ

フロントエンド インターフェイスをデータベースに接続するには、フロントエンド アプリケーションがデータを取得および送信できるようにする API を設計する必要があります。これにより、アカウントの作成、サインインとサインアウトなどのユーザー ロジックが有効になります。これにより、ローストに関するすべてのロジックが有効になります。

以前に Express API を作成したことがありますが、今回はビルド プロセスで Swagger についてもう少し詳しく学べるかどうかを確認したいと思いました。

ザ スワッガー スイート

Swagger は、Swagger Editor、Swagger CodeGen、Swagger UI の 3 つの製品を設計および保守する会社です。これら 3 つの製品が連携して動作することで、OpenAPI 準拠のアプリケーション (およびドキュメント) の作成が容易になります!

契約の使用

Swagger を使用して API を作成するプロセスは、Swagger エディターから始まります。このツールを使用すると、いわゆる契約を作成できます。コントラクトは、名前、処理するルートなど、アプリケーションに関するさまざまなことを定義する YAML ドキュメントです。

YAML と JSON

これまでに YAML を使用したことがない方のために説明すると、YAML は、JSON とある程度似ている、より緩やかなオブジェクトベースのマークアップ言語ですが、素早く入力するのがはるかに簡単です。同じコンテンツを JSON で表現し、次に YAML で表現した例を次に示します。

// JSON Example
{
  "name": "ThisApp",
  "description": "An example of data.",
  "list": [
    "option1",
    "option2",
    "option3"
  ],
  "object": {
    "key": "value"
  }
}
# YAML Example
name: ThisApp
description: An example of data.
list:
  - option1
  - option2
  - option3
object:
  key: value

YAML は機械可読であると同時に、人間にとっても読みやすいため、この仕様にとって優れたマークアップ言語であることに注意してください。

API仕様の定義

Swagger Editor を使用し、OAS に従って、通常プログラムするすべてのものを API に書き出すことができます。

トップレベルで、アプリケーションの詳細を定義します。

openapi: 3.0.3
info:
  title: Roast - Know Your Home Roasts
  description: # This will appear in the API UI
  version: 1.0.0
servers:
  - url: # A url to one or more servers here
tags:  These are groups of paths
  - name: user
    description: Operations for your user
  - name: roast
    description: Access to roasts
paths:
  # Define all of your paths in this object
components:
  # Define reusable pieces of code here

パスの定義を開始すると、CodeEditor の魔法が発揮されます。 ID で単一のローストを取得するために定義した次のパスをたどります。

# ... contract information
paths:
  # ... users paths, etc.
  /roasts/{roastId}:
    get:
      tags:
        - roast
      summary: Get roast by id
      description: Must include a valid roast id
      parameters:
        - $ref: '#/components/parameters/roastIdParam'
      responses:
        '200': 
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Roast"
        '400':
          $ref: '#/components/responses/Invalid'
        '404':
          $ref: '#/components/responses/NotFound'

このオブジェクトを分解してみましょう。まず、これは /roasts/{roastId} と呼ばれます。これは、リクエストがこのルートに送信されたときのサーバーの予期される動作を定義していることを意味します。その下では何が起こるでしょうか?

  • get: これは、このパスの GET リクエスト エンドポイントを定義したいことを Swagger ツールに伝えます。GET リクエストに関する残りの情報はそのオブジェクト内にあります。
  • タグ: これはエンドポイントのオプションのプロパティですが、ドキュメント内でエンドポイントをグループ化できるため、UI では便利です。
  • 概要: および説明: Swagger UI の画面上レンダリングでは、これらのフィールドの両方が異なる場所に表示されます。 「概要」にはエンドポイントの機能の簡単な説明が記載されており、「説明」には追加の詳細が記載されています。
  • パラメータ: get: のこのプロパティでは、パス パラメータを指定できます。パラメーターが必須かどうか、予期されるデータの種類などの情報を含めることができます。
  • 回答: これが肉とジャガイモです。エンドポイントからの有効な応答はステータス コード文字列として識別され、ドキュメント化とコード生成の目的でここにリストされます。

コンポーネントをドライに保つ

このような契約書を作成すると、同じ内容を何度も入力することになるでしょう。そして、プログラマならご存知かもしれませんが、「同じことを繰り返さない」という DRY 原則に従いたいと考えています。たとえば、必須のリクエスト本文を定義する場合、同じオブジェクトを必要とする可能性のあるエンドポイントが複数存在します。

ここでコンポーネントが登場します。この例では、スキーマを定義し、$ref を使用してコントラクト内の任意の場所でそのスキーマを参照できます。

つまり、コントラクトの最後に、コンポーネント: オブジェクトがあります。

components:
  schemas:
    Roast: # An arbitrary name to identify the schema
      type: object
      properties:
        id:
          type: integer
          format: int64
          example: 10
        ## Include all other properties

このコンポーネント オブジェクトには Roast というスキーマが含まれているため、このオブジェクトをリクエスト、たとえば /roast への POST リクエストで送信して新しいローストを追加する必要があることを指定する必要があります。この方法でオブジェクトを参照できます:

/roast:
  post:
    # additional specifications
    requestBody:
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Roast'

パラメータや仕様の他の多くの繰り返しセクションを定義する際にもこれを行うことができます!

自動文書化

Swagger エディターで入力している間、右側のウィンドウで Swagger UI が常に更新されています。 Swagger UI は、API ドキュメントとなるものを更新しています。これは、後で戻って自分でドキュメントを書き出す必要がないことを意味します。

Swagger Editor and UI

Swagger UI Endpoint

これの最も良い点は、(CodeGen を使用してアプリケーションを作成している限り) アプリケーションと一緒に提供されることです。

Let Swagger Code Your API Too!

Once you feel like your API is up to spec, you can have a working server in 17 different languages/frameworks in seconds! Just click Generate Server, and select your flavor and CodeGen reads your OAS spec and downloads a server.

In Node, your code comes out in a few different directories.

generated-server/
|-- api/
|-- controllers/
|-- service/
|-- utils/
|-- README.md
|-- index.js
|-- package.json

The api directory contains your OpenAPI spec. The controllers directory contains a file for each of your path groups, with exported functions specifically for handling the unique paths and operations of your application. The service directory, is where you will hook these operations up to your database and perform the business logic of the application, and utils contains functions that help read and write data.

Your server will actually live in index.js.

Is It Really That Easy?

Yes! Well, sort of.

CodeGen does in fact make a working server for you, but it's still up to you to hook up the database and design the logic of the application! But, it gives you a complete and organized skeleton that you can work in!

Here's an example of the code that it output for my POST request to /roasts .

// controllers/Roast.js
// ...
module.exports.addRoast = function addRoast (req, res, next, body) {
  Roast.addRoast(body)
    .then(function (response) {
      utils.writeJson(res, response);
    })
    .catch(function (response) {
      utils.writeJson(res, response);
    });
};

// service/RoastService.js
// ...
exports.addRoast = function(body) {
  return new Promise(function(resolve, reject) {
    var examples = {};
    examples['application/json'] = {
  "notes" : "Doesn't taste as good as last time... I wonder if the weather is making the beans roast faster now that it's warmer",
  "heatLevel" : "Med",
  "origin" : "Ethiopian",
  // ...
  "id" : 10,
};
    if (Object.keys(examples).length > 0) {
      resolve(examples[Object.keys(examples)[0]]);
    } else {
      resolve();
    }
  });
}

The above code was entirely generated by Swagger CodeGen. However, it won't actually add a roast object anywhere. This is creating a mock object and sending it back. But, after hooking up a Postgres database, and creating queries with this logic inside the service, the API will be fully operational!

Would You Use It?

I loved working with Swagger on this API, it was the first time that I committed to learning some of the intricacies of OAS to generate the server. The only rub that I have with it is that the docs are not formatted the best, and they can be hard to navigate searching for what you want to add to the server.

But, once you're familiar with OAS, this tool can save a ton of time. Not only do you have extremely thorough documentation when you're done, but you can treat the generated code as a to-do list of the functions and logic that you need to implement as you build!

Would you give it a try?


Check Out the Project

If you want to keep up with the changes, fork and run locally, or even suggest code changes, here’s a link to the GitHub repo!

https://github.com/nmiller15/roast

The frontend application is currently deployed on Netlify! If you want to mess around with some features and see it in action, view it on a mobile device below.

https://knowyourhomeroast.netlify.app

Note: This deployment has no backend api, so accounts and roasts are not actually saved anywhere between sessions.

以上が[Roast: Day - AI を使用せずに API サーバーを自動作成する]の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。