仓库源文站点原文


layout: "../layouts/BlogPost.astro" title: "Intro to GraphQL" slug: intro-to-graphql description: "" added: "Nov 7 2022" tags: [web]

updatedDate: "Nov 07 2022"

HTTP is commonly associated with REST, which uses "resources" as its core concept. In contrast, GraphQL's conceptual model is an entity graph. It was created by Facebook in 2012 and open-sourced in 2015. GraphQL is not dealing with dedicated resources. Instead everything is regarded as a graph and therefore is connected. You can combine different entities in one query and you are able to specific which attributes should be included in the response on every level.

It is common to fetch more data than you need in REST as each endpoint includes a settled data formation. There are situations where you may need only 2-3 values but you get around 20-25 values as the response. Similarly, with REST it’s comparatively easier to under fetch the dataset, enabling clients to make additional requests to get relevant data. GraphQL provides a declarative syntax that allows clients to specify which fields they need exactly, so the clients can only get what they actually need from the server.

A GraphQL server operates on a single URL endpoint, usually /graphql, and all GraphQL requests for a given service should be directed at this endpoint. When receiving an HTTP GET request, the GraphQL query should be specified in the ?query query string. A standard GraphQL POST request should use the application/json content type, and include a JSON-encoded body as the GraphQL query string.

Here are good resources to learn GraphQL:

GraphQL client and server implementations

A GraphQL implementation can be written with any programming language, integrate with any type of database, and support any client (such as mobile or web applications), as long as it follows the rules outlined in the specification. The GraphQL server describes the capabilities exposed in the API, and the client describes the requirements of the request. (A simple XMLHttpRequest or fetch from a web browser is sufficient for making requests by sending a GraphQL document to a GraphQL server.)