简单来说GraphQL 比起 RESTful 集成额外一些功能
这些都是优点了。
开发效率在项目初期是很重要的,需要快速原型化。
但是后期稳定后,性能也很重要。
from sanic import Sanic, text
from pydantic import BaseModel
from typing import List
app = Sanic("simple")
class Simple(BaseModel):
name: str
age: int
hobbies: List[str]
@app.post("/rest")
async def rest_test(request):
Simple.model_validate(request.json)
return text("ok")
import { check } from 'k6';
import http from 'k6/http';
export default function () {
let data = { "name": "Stephen Ling", "age": 28, "hobbies": ["coding", "coffee"] }
const res = http.post('http://localhost:9090/rest', JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
});
check(res, {
'is status 200': (r) => r.status === 200,
});
}
import { check } from 'k6';
import http from 'k6/http';
export default function () {
let data = {
"query": "mutation {\n resolveGraphql(name: \"Stephen Ling\", age: 28, hobbies: [\"coding\", \"coffee\"])\n}"
}
const res = http.post('http://localhost:9090/graphql', JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
});
check(res, {
'is status 200': (r) => r.status === 200,
});
}
import strawberry
from strawberry.sanic.views import GraphQLView
from sanic import Sanic, text
from pydantic import BaseModel
from typing import List
app = Sanic("simple")
@strawberry.type
class Mutation:
@strawberry.mutation
async def resolve_graphql(self, name: str, age: int, hobbies: List[str]) -> str:
return "ok"
@strawberry.type
class Query:
@strawberry.field
async def nothing(self) -> None:
...
app.add_route(
GraphQLView.as_view(
schema=strawberry.Schema(
query=Query,
mutation=Mutation,
),
),
"/graphql",
)
...
from strawberry.extensions import ParserCache, ValidationCache
...
app.add_route(
GraphQLView.as_view(
schema=strawberry.Schema(
query=Query,
mutation=Mutation,
extensions=[ParserCache(), ValidationCache()],
),
),
"/graphql",
)