如何通过Stepzen调用Google Books API获取20本评分最高书籍?
解决Stepzen对接Google Books API获取高评分书籍的查询错误
错误原因
Stepzen封装的googleBooksSearch字段并未定义orderBy参数,直接传递该参数会触发Unknown argument orderBy on field "Query.googleBooksSearch"错误。此外,Google Books API本身的orderBy参数仅支持relevance(默认)和newest两个取值,并不支持按评分排序的rating选项。
正确查询写法
要获取高评分书籍,需利用Google Books的搜索筛选语法,在q参数中指定评分阈值,结合maxResults限制返回数量:
query GetTopRatedBooks { googleBooksSearch(q: "rating:>=4.5", country: "US", maxResults: 20, printType: "books") { items { id volumeInfo { title subtitle authors averageRating ratingsCount description imageLinks { thumbnail } } } } }
参数说明
q: "rating:>=4.5":筛选平均评分≥4.5的书籍,可根据需求调整评分阈值printType: "books":限定返回结果为书籍类型,排除杂志等非书籍内容maxResults:20:返回最多20条符合条件的结果
如果需要更精准的结果(避免少量评价的极端高分书籍),可加入评价数量筛选:
query GetTopRatedBooks { googleBooksSearch(q: "rating:>=4.5 ratingsCount:>=100", country: "US", maxResults: 20, printType: "books") { items { id volumeInfo { title subtitle authors averageRating ratingsCount description imageLinks { thumbnail } } } } }
扩展:添加orderBy参数支持(可选)
如果需要使用orderBy参数(如按最新发布排序),可修改Stepzen的schema文件,将该参数映射到Google Books API的请求参数:
- 找到定义
googleBooksSearch的schema文件,修改字段参数:
type Query { googleBooksSearch(q: String, country: String, maxResults: Int, printType: String, orderBy: String): GoogleBooksSearchResult }
- 更新
@rest指令,将orderBy参数加入请求URL:
type Query { googleBooksSearch(q: String, country: String, maxResults: Int, printType: String, orderBy: String): GoogleBooksSearchResult @rest( endpoint: "https://www.googleapis.com/books/v1/volumes?q={{.Get "q"}}&country={{.Get "country"}}&maxResults={{.Get "maxResults"}}&printType={{.Get "printType"}}&orderBy={{.Get "orderBy"}}" headers: { "Accept": "application/json" } ) }
重新部署Stepzen后,即可在查询中使用orderBy: "newest"或orderBy: "relevance"参数。
内容的提问来源于stack exchange,提问作者anatoliya
相关产品推荐
相关产品推荐

