昨天簡單介紹後,今天又要來實作啦~
??提醒,如果是利用Homebrew or Linuxbrew 裝 Python的話 pip install 'strawberry-graphql'會有問題!如下圖
DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621
⭐️解決方法:
step1. python3 -m venv {環境名稱}
step2. source ./{環境名稱}/bin/activate
step3. pip strawberry-graphql[debug-server] or strawberry-graphql[fastapi]
好啦!不囉嗦要開始實作囉~
└──demo
    └──app.py
    └──data.py
    └──main.py
    └──model.py
    └──demo_graph      ##這邊虛擬環境的一包就不列出來 demo_graph是環境名稱
# -*- coding: utf-8 -*-
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
from app import schema
graphql_app = GraphQLRouter(schema)
app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")
# -*- coding: utf-8 -*-
import typing
import strawberry
from datetime import datetime
# 用戶資料
@strawberry.type
class User:
    UserID: str
    IsLogin: bool
    Created_at: datetime
# 飲料資訊
@strawberry.type
class Drink:
    channel: str
    name: str
    info: str
來對照API文件頁面~
用戶資料頁面
飲料資料頁面
app.py query資料的架構
# -*- coding: utf-8 -*-
import strawberry
import typing
from data import (
    get_users, get_drinks
)
from model import (
    User, Drink
)
@strawberry.type
class Query:
    users: User = strawberry.field(resolver=get_users)
    drinks: typing.List[Drink] = strawberry.field(resolver=get_drinks)
schema = strawberry.Schema(Query)
# -*- coding: utf-8 -*-
"""
取得資料
"""
from datetime import datetime
from pymongo import MongoClient
from model import (
    User, Drink
)
#%%
client = MongoClient('localhost:27017', username='帳號', password='密碼')
#%%
# 取得用戶資料
def get_users():
    return User(
        UserID='Mary',
        IsLogin=False,
        Created_at=datetime.now()
    )
# 取得飲料資料
def get_drinks():
    data = list(
        client['Shop']['Drink'].find(
            {}, {'_id':0, 'channel':1, 'name':1, 'info':1}
        ).limit(3)
    )
    
    return list(Drink(
        channel = item.get('channel'),
        name = item.get('name'),
        info = item.get('info'),
    ) for item in data)

ps. 碎碎念時間:越研究就發現好多東西可以說明,我也是新學啦?,果然鐵人賽還是要學些新東西深入挖掘,好有趣哈哈,上個小主題的Restful API 寫過太多次感覺有點沒熱情,不過範例跟結構是非常實用的喔~希望大家能多瞭解它的特色規範,GraphQL新一些,我看範例也蠻少的,就讓我再寫幾天吧~
哎趁這個時間多經營一下好了程式碼連結
資料參考