An Introduction to GraphQL

Josh O'leary
2 min readFeb 10, 2023
unsplash — casparrubin

GraphQL is a query language designed to replace traditional REST APIs. It was developed by Facebook and has gained widespread popularity in recent years, with many large companies such as GitHub, Shopify, and Airbnb adopting it. The key advantage of GraphQL over REST is its ability to allow clients to request only the data they need, in a single request. This eliminates the need for multiple requests to multiple endpoints to gather all the required data, making it more efficient and flexible.

GraphQL queries are written in a specific syntax and are used to specify the data that should be returned from the server. A query is made up of a set of fields that correspond to the data being requested. These fields can also contain sub-fields for nested data structures. The query is then sent to the server, which returns a JSON response that matches the shape of the query.

Here is an example of a simple GraphQL query in JavaScript:

query {
user(id: "123") {
name
email
}
}

In this example, the query is asking for data about a user with an ID of “123”. The two fields in the query, “name” and “email”, correspond to the data that should be returned. The server will respond with a JSON object that contains only the requested data.

GraphQL also provides advanced features such as subscriptions, which allow for real-time updates, and mutations, which allow for changes to be made to data on the server. Here is an example of a mutation in GraphQL using JavaScript:

mutation {
createUser(input: { name: "John", email: "john@example.com" }) {
user {
name
email
}
}
}

In this example, the mutation creates a new user with a name of “John” and an email of “john@example.com”. The response from the server will contain the newly created user, with the name and email fields as specified in the query.

GraphQL also provides strong type systems and a schema, which define the structure of the data being queried. This acts as a contract between the client and the server, making development more efficient and providing better documentation. The schema can be written in the GraphQL Schema Definition Language (SDL), which is a simple syntax for defining the structure of the data in a GraphQL API.

In conclusion, GraphQL offers a more efficient and flexible way of querying APIs, with advanced features such as real-time updates and mutations. Its strong type systems, schema, and simple syntax make it a compelling alternative to traditional REST APIs.

--

--

Josh O'leary

Full-stack web developer who is passionate about learning and creating!