GraphQL - Alternative to REST API
GraphQL is an API query language that is built on a simple and flexible type system. It is designed to be independent of any specific database or storage system, and can be used to fetch data from a wide range of sources.
It was invented by Facebook to address the challenges that arose as their platform grew and evolved. Facebook's API was originally built using REST principles, which made it easy to add new endpoints and support a wide range of clients. However, as the platform grew and the number of endpoints and clients increased, it became more difficult to manage and optimize the API.
One of the key challenges was over-fetching and under-fetching of data. REST APIs typically return a fixed set of data for each endpoint, which means that clients may receive more data than they need, or need to make multiple requests to fetch all the data they require. This can lead to inefficiencies and slow performance, especially on mobile devices or in low-bandwidth environments.
It was originally designed to address these issues by providing a more flexible and efficient way to fetch data from an API. With GraphQL, clients can specify exactly what data they need, and the server returns only that data. This means that clients can avoid over-fetching or under-fetching data, and can get the data they need in a single request.
Another benefit of GraphQL is that it provides a strongly-typed schema that describes the data available from the API, as well as the relationships between different types of data. This makes it easier for clients to understand the API and to construct queries that fetch the data they need.
The architecture is based on three key components:
Here's an example of how to use the if directive in a GraphQL query:
query {
host(id: cef8564) {
??name
领英推荐
??listings {
???title
???address
???isVerified @if(flag: true)
??}
?}
}
Explanation: This query returns name, email and listings from the server which has a schema named host which has an id of 'cef8564' and isVerified column is returned only of flag is true.
The return data is a JSON object.