概述
本文將展示如何使用Postman測(cè)試GraphQL服務(wù)。以如下Schema為例:
type Post {
    id: ID!
    title: String!
    text: String!
    category: String
    author: Author!
}
 
type Author {
    id: ID!
    name: String!
    thumbnail: String
    posts: [Post]!
}
    
type Query {
    recentPosts(count: Int, offset: Int): [Post]!
}
 
type Mutation {
    createPost(title: String!, text: String!, category: String) : Post!
}點(diǎn)擊“New API”,選擇“GraphQL類型”,然后按“Generate Collection”,就可以使用Postman對(duì)GraphQL支持的自動(dòng)完成功能,很方便地編寫(xiě)示例查詢。

GraphQL請(qǐng)求
Postman允許以GraphQL格式發(fā)送正文,選擇下面的GraphQL類型:

然后,我們可以編寫(xiě)一個(gè)原生GraphQL查詢:
query {
    recentPosts(count: 1, offset: 0) {
        title
        category
        author {
            name
        }
    }
}響應(yīng)報(bào)文如下:
{
    "data": {
        "recentPosts": [
            {
                "title": "Post",
                "category": "test",
                "author": {
                    "name": "Author 0"
                }
            }
        ]
    }
}使用變量
在變量部分,我們可以創(chuàng)建一個(gè)JSON格式的模式,為變量賦值:

query recentPosts ($count: Int, $offset: Int) {
    recentPosts (count: $count, offset: $offset) {
        id
        title
        text
        category
    }
}編輯GRAPHQL VARIABLES部分,其中包含希望將變量設(shè)置的值:
{
  "count": 1,
  "offset": 0
}總結(jié)
使用Postman可以很方便地測(cè)試GraphQL,也允許我們導(dǎo)入Schema并生成查詢。