id: Int!
title: String!
description: String
}

在這里,Movie 是一個(gè)對(duì)象類型,其字段包括 id、標(biāo)題和描述。感嘆號(hào)(!)因此,該類型中 id 和 title 是必填字段,而 description 是可選字段。

查詢類型

它是一種特殊的對(duì)象類型,為查詢提供入口點(diǎn)。所有查詢都在該對(duì)象中定義。

type Query{
# Define queries here
}

獲取 API 中的所有電影,我們將定義一個(gè) movie 查詢:

type Query {
movies: [Movie!]!
}

如您所見,我們還將查詢返回的數(shù)據(jù)指定為 [Movie!]!。這種語(yǔ)法意味著它將始終返回一個(gè)數(shù)組,而數(shù)組中的每個(gè)元素都是一個(gè) movie 對(duì)象。

現(xiàn)在,如果我們想獲取一部特定的電影怎么辦?我們可以這樣定義 movie 查詢:

type Query {
movies: [Movie!]!
movie(id: Int!): Movie
}

movie 查詢需要一個(gè) id 參數(shù),即我們要獲取的 movie id。然后返回一個(gè) movie 對(duì)象。

用法

現(xiàn)在,我們可以這樣使用這些查詢:

# Fetches all the movies
query movies {
id
title
description
}
# Fetches a particular movie
query movie(id: 200) {
id
title
description
}

定義 GraphQL 突變

與查詢一樣,您可以在突變類型中定義突變

突變類型

比方說(shuō),我們希望允許一個(gè)突變來(lái)創(chuàng)建一部新 movie。我們可以這樣定義 create Movie 突變:

type Mutation {
createMovie(title: String!, description: String): Movie
}

它將接受標(biāo)題和描述并創(chuàng)建一部新 movie。最后,它會(huì)在響應(yīng)中返回一個(gè)新添加 movie 的 Movie 對(duì)象。

用法

我們可以這樣使用突變:

query createMovie(title: "The Matrix", description: "A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.") {
id
title
description
}

如果我們運(yùn)行這個(gè)突變,API 將返回這樣的數(shù)據(jù):

{
"data": {
"createMovie": {
"id": 200,
"title": "The Matrix",
"description": "A computer hacker learns from mysterious rebels about the true nature ofhis reality and his role in the war against its controllers."
}
}
}

就是這樣。您可以看到,在模式中定義查詢和突變是多么容易?,F(xiàn)在,您只需創(chuàng)建解析器函數(shù)來(lái)處理它們,您的 API 就可以正常運(yùn)行了。

原文鏈接:How to Define GraphQL Queries and Mutations?

上一篇:

調(diào)用 GraphQL API 需要做的 4 件事

下一篇:

網(wǎng)頁(yè)抓取與API有什么區(qū)別?
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)