An open API service indexing awesome lists of open source software.

https://github.com/riii111/fastapi-graphql-sample

技術検証用。FastAPIにGraphQL導入
https://github.com/riii111/fastapi-graphql-sample

fastapi graphql mongodb python

Last synced: 5 months ago
JSON representation

技術検証用。FastAPIにGraphQL導入

Awesome Lists containing this project

README

          

※RESTとGraphQLを併用できる形で実装。

# GraphQL memo

## GUI

## GraphQLのフロー

GraphQL、REST併用することを想定しているので、usecaseやmodel、repositoryを経由する。
"Book"に対してQuery/Mutationを行う場合のフロー。

```mermaid
graph TD
Client[Client] -->|GraphQL Query| Router[GraphQL Router]
Router -->|Executes| Schema["Federation Schema (Query)"]
Schema -->|Defines & Resolves| Query[Query]
Query -->|Resolves| Resolvers[Resolvers]
Resolvers -->|Uses| Context[GraphQL Context]
Context -->|Depends on| BookUseCase[Book UseCase]
BookUseCase -->|Uses| BookRepository[Book Repository]
BookRepository -->|Accesses| Database[(Database)]

Resolvers -->|Returns| BookType[BookType]
BookType -->|Defined in| Types[Types]
Types -->|Uses| PyObjectIdType[PyObjectIdType]

subgraph "GraphQL Layer"
Router
Schema
Query
Resolvers
Context
BookType
Types
PyObjectIdType
end

subgraph "Business Logic Layer"
BookUseCase
end

subgraph "Data Access Layer"
BookRepository
end

subgraph "Models"
Book[Book Model]
PyObjectId[PyObjectId Model]
end

BookType -.->|Maps to| BookResponse
PyObjectIdType -.->|Serializes| PyObjectId

classDef graphql fill:#e6f3ff,stroke:#333,stroke-width:2px,color:#000;
classDef business fill:#fff2cc,stroke:#333,stroke-width:2px,color:#000;
classDef data fill:#e6ffee,stroke:#333,stroke-width:2px,color:#000;
classDef model fill:#ffe6e6,stroke:#333,stroke-width:2px,color:#000;

class Router,Schema,Query,Resolvers,Context,BookType,Types,PyObjectIdType graphql;
class BookUseCase business;
class BookRepository data;
class BookResponse,PyObjectId model;

linkStyle default fill:none,stroke:#333,stroke-width:2px;
```

## 動作確認例

### books一覧を取得する場合

image

### 対象のIDのbookを取得する場合

image

### 新しいbookを作成する場合

image

### bookを更新する場合

image

### bookを削除する場合

image

## ざっくりメモ

- **クエリ (Query)**

データを取得するためのリクエスト

クライアントが必要なデータの構造を指定し、その構造に基づいてサーバーからデータが返される

- **ミューテーション (Mutation)**

データを変更するためのリクエスト

新しいデータの作成、既存データの更新、削除などが含まれる

- **サブスクリプション (Subscription)**

特定のイベントが発生した際に、クライアントにリアルタイムで通知を送信する仕組み

主にチャットアプリや通知機能で利用される

- **スキーマ (Schema)**

GraphQL APIの仕様を定義するもの

どのようなデータ型が存在し、それらがどのように関連しているかを示す

スキーマは型システムに基づいており、APIの設計を明確にする

- **型 (Type)**

GraphQLで使用されるデータ型

基本的なスカラー型(String, Int, Float, Boolean, ID)やオブジェクト型などがある

- **リゾルバ (Resolver)**

特定のフィールドに対してデータを取得するための関数

リゾルバはスキーマで定義されたフィールドに基づいて実行される