文件名称 | 版本号 | 作者 | 版本 | |
---|---|---|---|---|
Python API开发,FastAPI之Graphql版本! | v1.0.2 | 学生宫布 | 8416837 | Python 3.8 FastAPI (0.1.0) |
源码
Demo
简介
- Graphql是一种神奇的技术,它是API查询语言,传什么参数获得啥结果,等等神奇妙用。进入官网
- Graphql不受编程语言限制,Java、Python、JavaScript、C# / .NET等等都支持。查看支持的语言
安装
安装FastAPI见 FastAPI安装教程
试水
使用Conda
- 当前使用的是Conda 4.8.2。安装教程:查看教程
- 安装依赖库
pip3 install graphene
使用IDE开发 比如:PyCharm
配置
- 如果已经打开了项目窗口,则新建Python Package
- 新建文件等:
代码
- 向main.py拷入代码:
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
def resolve_hello(self, info, name):
return "Hello " + name
app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))
- 安装依赖库 否则会报错如下:
安装:
pip3 install graphene
启动项目
- 打开gitbash,定位到main.py所在目录,执行命令:
uvicorn main:app --reload
访问项目
启动完毕,访问项目
页面解释
- UI
- 释义
调用Graphql API
- 传入参数,获得响应:
之所以传入{hello}
,可以获得响应:
{
"data": {
"hello": "Hello stranger"
}
}
是因为代码里写了这个接口解析,它是这样的:
- 参数更复杂一点:
进阶
- 将代码整得稍微复杂一点:
import json
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
def resolve_hello(self, info, name):
return "Hello " + name
login_in = graphene.String(username=graphene.String(default_value="administrator"))
def resolve_login_in(self, info, username):
data = [{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]
json2 = json.dumps(data)
return "Hello " + username
app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))
执行,获得响应:
- 加个判断:
import json
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp
# 生成gql的Query
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="stranger"))
def resolve_hello(self, info, name):
return "Hello " + name
login_in = graphene.String(username=graphene.String(default_value="administrator"))
def resolve_login_in(self, info, username):
return "Hello " + username
login = graphene.String(username=graphene.String(default_value="administrator"))
graphene.ObjectType
def resolve_login(self, info, username):
name = '李甲'
if(name.__eq__(username)):
data = [{'username': '李甲', 'b': 2, 'c': 3, 'd': 4, 'e': 5}]
json2 = json.dumps(data)
return json2
else :
return ""
app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))
响应: