
GraphQL API滲透測試指南
通過Graphene,你可以快速構建出一個支持按需查詢、實時更新的API服務。我們開始這段有趣的學習之旅吧!
先安裝Graphene:
pip install graphene
小貼士:如果你計劃與Django一起使用,可以安裝 graphene-django
。
在GraphQL中,Schema定義了API的類型系統。我們創建一個簡單的圖書管理系統:
import graphene
class Author(graphene.ObjectType):
"""作者信息"""
name = graphene.String(description="作者姓名")
books = graphene.List(lambda: Book, description="作者的作品")
class Book(graphene.ObjectType):
"""書籍信息"""
title = graphene.String(description="書籍標題")
author = graphene.Field(Author, description="作者")
pages = graphene.Int(description="頁數")
price = graphene.Float(description="價格")
# 創建查詢
class Query(graphene.ObjectType):
books = graphene.List(Book, description="所有書籍")
author = graphene.Field(
Author,
name=graphene.String(required=True),
description="根據姓名查詢作者"
)
def resolve_books(self, info):
"""獲取所有書籍"""
return get_books() # 實際項目中從數據庫獲取
def resolve_author(self, info, name):
"""根據姓名查詢作者"""
return get_author_by_name(name) # 實際項目中從數據庫獲取
schema = graphene.Schema(query=Query)
一句話總結:Schema是GraphQL API的骨架,定義了可查詢的數據結構和類型。
class CreateBook(graphene.Mutation):
"""創建新書籍"""
class Arguments:
title = graphene.String(required=True)
author_name = graphene.String(required=True)
pages = graphene.Int()
price = graphene.Float()
book = graphene.Field(Book)
def mutate(self, info, title, author_name, pages=None, price=None):
author = get_or_create_author(author_name)
book = create_book(title=title, author=author, pages=pages, price=price)
return CreateBook(book=book)
class Mutation(graphene.ObjectType):
create_book = CreateBook.Field()
# 更新schema
schema = graphene.Schema(query=Query, mutation=Mutation)
注意事項:
以Flask為例,讓我們創建一個GraphQL endpoint:
from flask import Flask
from flask_graphql import GraphQLView
app = Flask(__name__)
app.add_url_rule(
'/graphql',
view_func=GraphQLView.as_view(
'graphql',
schema=schema,
graphiql=True # 啟用GraphiQL界面
)
)
if __name__ == '__main__':
app.run(debug=True)
小貼士:GraphiQL是一個超好用的調試工具,可以直接在瀏覽器中測試查詢。
class SearchResult(graphene.Union):
"""搜索結果可能是書籍或作者"""
class Meta:
types = (Book, Author)
class Node(graphene.Interface):
"""可查詢節點的接口"""
id = graphene.ID(required=True)
class Book(graphene.ObjectType):
class Meta:
interfaces = (Node,)
from promise import Promise
from promise.dataloader import DataLoader
class AuthorLoader(DataLoader):
def batch_load_fn(self, keys):
authors = get_authors_by_ids(keys) # 批量查詢作者
return Promise.resolve([
next((a for a in authors if a.id == key), None)
for key in keys
])
# 在resolve方法中使用
def resolve_author(self, info):
return info.context.author_loader.load(self.author_id)
今天我們學習了:
練習題:
實踐建議:
GraphQL提供了極大的靈活性,但也需要我們合理設計Schema以避免過度復雜。希望這篇教程能幫助你開啟GraphQL之旅!??
文章轉自微信公眾號@愛刷牙的雙髻鯊
GraphQL API滲透測試指南
Python + BaiduTransAPI :快速檢索千篇英文文獻(附源碼)
掌握ChatGPT API集成的方便指南
node.js + express + docker + mysql + jwt 實現用戶管理restful api
nodejs + mongodb 編寫 restful 風格博客 api
表格插件wpDataTables-將 WordPress 表與 Google Sheets API 連接
手把手教你用Python和Flask創建REST API
使用 Django 和 Django REST 框架構建 RESTful API:實現 CRUD 操作
ASP.NET Web API快速入門介紹