GraphQL 是一种用于 API 开发的查询语言,由 Facebook 开发。与传统的 REST API 不同,GraphQL 允许客户端指定所需的数据结构,从而避免了过多的数据传输。使用 Python 开发 GraphQL API 可以利用诸如 Graphene
、Ariadne
等库。
Graphene
开发 GraphQL APIGraphene
是一个流行的 Python 库,用于构建 GraphQL API。
Graphene
pip install graphene
以下示例展示了如何使用 Graphene
创建一个简单的 GraphQL API。
import graphene
class User(graphene.ObjectType):
id = graphene.ID()
username = graphene.String()
email = graphene.String()
class Query(graphene.ObjectType):
users = graphene.List(User)
def resolve_users(self, info):
return [
User(id=1, username="alice", email="alice@example.com"),
User(id=2, username="bob", email="bob@example.com"),
]
schema = graphene.Schema(query=Query)
users
查询,返回一个用户列表。接下来,将 GraphQL Schema 暴露为一个可访问的 API 端点。以下示例展示了如何使用 Flask 将 GraphQL 集成到 Web 应用中。
pip install flask graphene flask-graphql
from flask import Flask
from graphene import Schema
from flask_graphql import GraphQLView
import graphene
# 定义 User 类型
class User(graphene.ObjectType):
id = graphene.ID()
username = graphene.String()
email = graphene.String()
# 定义 Query
class Query(graphene.ObjectType):
users = graphene.List(User)
def resolve_users(self, info):
return [
User(id=1, username="alice", email="alice@example.com"),
User(id=2, username="bob", email="bob@example.com"),
]
# 创建 Flask 应用
app = Flask(__name__)
# 创建 Schema
schema = Schema(query=Query)
# 配置 GraphQL 视图
app.add_url_rule(
"/graphql",
view_func=GraphQLView.as_view("graphql", schema=schema, graphiql=True)
)
if __name__ == "__main__":
app.run(debug=True)
GraphQLView
类,将 GraphQL Schema 公开为一个 API 端点。运行服务器后,可以通过浏览器访问 http://localhost:5000/graphql
,使用 GraphiQL 界面测试 GraphQL 查询:
{
users {
id
username
email
}
}
Mutations 用于修改服务器端数据,例如创建、更新或删除记录。以下示例展示了如何定义和使用 Mutation。
class CreateUser(graphene.Mutation):
class Arguments:
username = graphene.String(required=True)
email = graphene.String(required=True)
user = graphene.Field(lambda: User)
def mutate(self, info, username, email):
user = User(username=username, email=email)
return CreateUser(user=user)
class Mutation(graphene.ObjectType):
create_user = CreateUser.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
在 GraphiQL 中测试 Mutation:
mutation {
createUser(username: "charlie", email: "charlie@example.com") {
user {
id
username
email
}
}
}
Ariadne
开发 GraphQL APIAriadne
是另一个构建 GraphQL API 的 Python 库,使用 SDL(Schema Definition Language)定义 GraphQL Schema。
Ariadne
pip install ariadne
from ariadne import QueryType, make_executable_schema, graphql_sync
from ariadne.constants import PLAYGROUND_HTML
from flask import Flask, request, jsonify
type_defs = """
type Query {
hello: String!
}
"""
query = QueryType()
@query.field("hello")
def resolve_hello(_, info):
return "Hello, world!"
schema = make_executable_schema(type_defs, query)
app = Flask(__name__)
@app.route("/graphql", methods=["GET"])
def graphql_playground():
return PLAYGROUND_HTML, 200
@app.route("/graphql", methods=["POST"])
def graphql_server():
data = request.get_json()
success, result = graphql_sync(schema, data, context_value=request, debug=app.debug)
status_code = 200 if success else 400
return jsonify(result), status_code
if __name__ == "__main__":
app.run(debug=True)
Graphene-Django
如果你在使用 Django 开发,可以使用 Graphene-Django
将 GraphQL 集成到 Django 项目中。
Graphene-Django
pip install graphene-django
在 settings.py
中添加 graphene_django
到 INSTALLED_APPS
:
INSTALLED_APPS = [
...
'graphene_django',
]
GRAPHENE = {
'SCHEMA': 'myproject.schema.schema' # 指向你的 Schema 定义
}
from django.db import models
import graphene
from graphene_django import DjangoObjectType
class User(models.Model):
username = models.CharField(max_length=100)
email = models.EmailField()
class UserType(DjangoObjectType):
class Meta:
model = User
class Query(graphene.ObjectType):
users = graphene.List(UserType)
def resolve_users(self, info):
return User.objects.all()
schema = graphene.Schema(query=Query)
在 urls.py
中添加 GraphQL 端点:
from django.urls import path
from graphene_django.views import GraphQLView
urlpatterns = [
path("graphql", GraphQLView.as_view(graphiql=True)),
]
无论是简单的 API 还是复杂的 Web 应用,使用 GraphQL 可以帮助你构建灵活、高效的数据接口。