当前位置: 首页 > 工具软件 > graphql-cli > 使用案例 >

简单api_GraphQL API集成的简要介绍

程磊
2023-12-01

简单api

GraphQL is a great alternative to REST (or other HTTP API designs). This is a quick introduction to the core concepts around consuming a GraphQL API.

GraphQL是REST(或其他HTTP API设计)的绝佳替代品。 这是对使用 GraphQL API的核心概念的快速介绍。

To see some examples consuming a GraphQL API:

要查看一些使用GraphQL API的示例:

什么是GraphQL,它可以解决什么问题? (What is GraphQL and what problems does it solve?)

GraphQL is “a query language for your API”.

GraphQL是“ API的查询语言”

In plain English, it makes the client define what (nested) data it needs.

用简单的英语,它使客户定义它需要什么(嵌套)数据。

If we compare it to REST approaches:

如果我们将其与REST方法进行比较:

  • the “pure” REST approach is to return IDs (or resource links) for any associations (or nested resources).

    “纯” REST方法是为任何关联(或嵌套资源)返回ID(或资源链接)。
  • The less pure approach is to expand all the nested stuff.

    不太单纯的方法是扩展所有嵌套的东西。

The first situation leads to having to make lots of calls to fetch all the data. The second leads to huge payloads and slow load times.

第一种情况导致必须进行大量调用才能获取所有数据。 第二个导致巨大的负载和较慢的加载时间。

In GraphQL, the client states in the request what it wants expanded, renamed or whatever else in the response.

在GraphQL中,客户端在请求中声明其要扩展,重命名的内容或响应中的其他内容。

It has some nice side-effects, for example less need to version your API since the client defines what it wants and GraphQL has a way to deprecate fields.

它具有一些不错的副作用,例如,由于客户端定义了所需的内容,并且GraphQL有一种弃用字段的方法,因此无需对API进行版本控制。

架构图 (Schema)

GraphiQL, “An in-browser IDE for exploring GraphQL.” is available by navigating to the endpoint in your browser. It’s possible to generate the schema using the GraphQL CLI (requires Node + npm 5+):

GraphiQL ,“用于浏览GraphQL的浏览器内置IDE。” 通过浏览到浏览器中的端点可以使用该功能。 可以使用GraphQL CLI生成模式(需要Node + npm 5+):

npx graphql-cli get-schema --endpoint $BASE_URL/api/graphql --no-all -o schema.graphql

查询 (Queries)

GraphQL查询概念 (GraphQL query concepts)

领域 (Fields)

What we would like returned in the query, see the GraphQL documentation for “fields”. The GraphQL query for that returns the fields name, fleeRate, maxCP, maxHP, is the following:

我们希望在查询中返回的内容,请参见GraphQL文档中的“字段” 。 用于其的GraphQL查询返回以下字段namefleeRatemaxCPmaxHP

{
  pokemon(name: "Pikachu") {
    name
    fleeRate
    maxCP
    maxHP
  }
}

争论 (Arguments)

How we are going to filter the query data down, see the GraphQL documentation for “arguments”. To get the names of the first 10 pokemon we use pokemons (first: 10) { FIELDS }to see the output here:

我们将如何向下过滤查询数据,请参见GraphQL文档中的“参数” 。 要获取前10个宠物pokemons (first: 10) { FIELDS }的名称,我们使用pokemons (first: 10) { FIELDS }此处查看输出:

{
  pokemons (first: 10) {
    name
    fleeRate
    maxCP
    maxHP
  }
}

别名 (Aliases)

Aliases give us the ability to rename fields. (See the GraphQL documentation for “aliases”). We’re actually going to use it to map fields in the query eg. from camel to snake case:

别名使我们能够重命名字段。 (请参阅GraphQL文档中的“别名” )。 我们实际上将使用它来映射查询中的字段,例如。 从骆驼到蛇的情况:

{
  pokemon(name: "Pikachu") {
    evolution_requirements: evolutionRequirements {
      amount
      name
    }
  }
}

Running this query (here) gives us the following, where the evolutionRequirements is what we’ve aliased it to.

运行此查询( 在此处 )将为我们提供以下内容,其中evolutionRequirements是我们为其别名的内容。

{
  "data": {
    "pokemon": {
      "evolution_requirements": {
        "amount": 50,
        "name": "Pikachu candies"
      }
    }
  }
}

碎片 (Fragments)

The definition of fields to be expanded on a type. It’s a way to keep the queries DRY and in general split out the field definitions that are repeated, re-used or deeply nested, see the GraphQL documentation for fragments. It’s going to mean that instead of doing (see the query in action here):

要在类型上扩展的字段的定义。 这是使查询保持DRY并通常拆分出重复,重复使用或深度嵌套的字段定义的一种方法,请参见GraphQL文档以获取片段 。 这将意味着而不是这样做( 请参阅 此处的查询 ):

{
  pokemon(name: "Pikachu") {
    weight {
      minimum
      maximum
    }
    height {
      minimum
      maximum
    }
  }
}

We can for example run this (query here):

我们可以例如运行以下命令( 在此处 查询 ):

{
  pokemon(name: "Pikachu") {
    weight {...FullPokemonDimensions}
    height {...FullPokemonDimensions}
  }
}
fragment FullPokemonDimensions on PokemonDimension {
  minimum
  maximum
}

The output is equivalent:

输出是等效的:

{
  "data": {
    "pokemon": {
      "weight": {
        "minimum": "5.25kg",
        "maximum": "6.75kg"
      },
      "height": {
        "minimum": "0.35m",
        "maximum": "0.45m"
      }
    }
  }
}

运行GraphQL查询 (Running a GraphQL query)

A GraphQL query can be run over POST or GET, it consists of:

GraphQL查询可以通过POST或GET运行,它包括:

POST(推荐) (POST (recommended))

  • Required headers: Content-Type: application/json

    必需的标头: Content-Type: application/json

  • Required JSON body parameter: query: { # insert your query }

    必需的JSON正文参数: query: { # insert your query }

Raw HTTP request

原始HTTP请求

POST / HTTP/1.1
Host: graphql-pokemon.now.sh
Content-Type: application/json
{
        "query": "{ pokemons(first: 10) { name } }"
}

cURL

卷曲

curl -X POST \
  https://graphql-pokemon.now.sh/ \
  -H 'Content-Type: application/json' \
  -d '{
        "query": "{ pokemons(first: 10) { name } }"
    }'

得到 (GET)

  • Required query param: query

    必需的查询参数: query

raw HTTP request

原始HTTP请求

GET /?query={%20pokemons(first:%2010)%20{%20name%20}%20} HTTP/1.1
Host: graphql-pokemon.now.sh

cURL

卷曲

curl -X GET 'https://graphql-pokemon.now.sh/?query={%20pokemons%28first:%2010%29%20{%20name%20}%20}'

顶级查询 (Top-level queries)

There are 2 types of queries on the GraphQL Pokemon API at the moment:

目前,在GraphQL Pokemon API上有两种查询类型:

  • First X pokemon: get all items (with whatever fields are defined in the query)

    第一个X宠物小精灵:获取所有物品(带有查询中定义的任何字段)
  • Single Pokemon by name: get a single item by its slug (with whatever fields are defined in the query)

    按名称命名的单个口袋妖怪:通过其子弹获得单个项目(查询中定义的任何字段)
  • Single Pokemon by id: get a single item by its slug (with whatever fields are defined in the query)

    按ID排列的单个口袋妖怪:按其子项获取单个项目(查询中定义的任何字段)

第一个X宠物小精灵 (First X Pokemon)

Queries of the form (see it in action in GraphiQL):

表单查询( 在GraphiQL中可以查看 ):

{
  pokemons(first: 5) {
    name
    # other fields
  }
}

单个口袋妖怪的名字 (Single Pokemon by name)

Queries of the form (see it in action in GraphiQL):

形式的查询( 在GraphiQL中可以查看 ):

{
  pokemon(name: "Pikachu") {
    name
    classification
    # other fields
  }
}

Note the double quotes ("") around the argument value

注意参数值周围的双引号( "" )

单口袋妖怪ID (Single Pokemon by id)

Queries of the form (see it in action in GraphiQL):

形式的查询( 在GraphiQL中可以查看 ):

{
  pokemon(id: "UG9rZW1vbjowMjU=") {
    name
    classification
    # other fields
  }
}

Note the double quotes ("") around the argument value

注意参数值周围的双引号( "" )

样本查询 (Sample queries)

获取一些神奇宝贝来创建优势/劣势/抵抗力分类 (Get some Pokemon to create strengths/weakness/resistance classification)

Query (see it in GraphiQL):

查询( 在GraphiQL中查看 ):

{
  pokemons(first: 100) {
    name
    image
    maxHP
    types
    weaknesses
    resistant
  }
}

获取口袋妖怪并扩展其物理统计数据和攻击范围 (Get Pokemon and evolutions expanded for physical stats and attacks)

Query (see it in GraphiQL):

查询( 在GraphiQL中查看 ):

{
  pokemon(name: "Pikachu") {
    ...PokemonWithAttack
    ...FullPhysicalStats
    evolutions {
      ...FullPhysicalStats
      ...PokemonWithAttack
    }
  }
}
fragment PokemonWithAttack on Pokemon {
  name
  attacks {
    fast {
      name
      type
      damage
    }
    special {
      name
      type
      damage
    }
  }
}
fragment FullPhysicalStats on Pokemon {
  height { ...FullDimension }
  weight { ...FullDimension }
}
fragment FullDimension on PokemonDimension {
  minimum
  maximum
}

获取选定的Pokemon作为其演化名称的命名字段 (Get selected Pokemon as named fields with their evolution names)

Query (see it in GraphiQL).

查询( 在GraphiQL中查看 )。

We can rename top-level queries using aliases. That’s helpful if we want to do the following:

我们可以使用别名重命名顶级查询。 如果我们要执行以下操作,这将很有帮助:

{
  pikachu: pokemon(name: "Pikachu") {
    ...FullPokemon
    evolutions {
      ...FullPokemon
    }
  }
  bulbasaur:pokemon(name: "Bulbasaur") {
    ...FullPokemon
    evolutions {
      ...FullPokemon
    }
  }
}
fragment FullPokemon on Pokemon {
  name
}

If you want to learn how to integrate with a GraphQL API:

如果您想学习如何与GraphQL API集成:

- In Python, see Python GraphQL client requests example using gql- In JavaScript browser and Node, see last week’s Code with Hugo newsletter

-在Python中,请参见使用gql的Python GraphQL客户端请求示例 -在JavaScript 浏览器和Node中,请参见上周的《带有Hugo的代码》时事通讯

Read more of my articles on my website, Code With Hugo.

在我的网站Code With Hugo上阅读更多文章。

翻译自: https://www.freecodecamp.org/news/a-gentle-introduction-to-graphql-api-integrations-6564312d402c/

简单api

 类似资料: