GraphQL for API Development

What is it?

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. It was originally created at Facebook in 2012 for describing the capabilities and requirements of data models for client-server applications.

Why is it relevant?

GraphQL gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. GraphQL queries always return predictable results. Apps using GraphQL are fast and stable because they control the data they get, not the server.

GraphQL APIs are organized in terms of types and fields, not endpoints. Access the full capabilities of your data from a single endpoint. GraphQL uses types to ensure Apps only ask for what’s possible and provide clear and helpful errors. Apps can use types to avoid writing manual parsing code.

GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.

How does GraphQL work?

A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type. For example, a GraphQL service that tells you who the logged in user is (me) as well as that user’s name might look like this:

type Query {
  me: User
}

type User {
  id: ID
  name: String
}

Along with functions for each field on each type:

function Query_me(request) {
  return request.auth.user;
}

function User_name(user) {
  return user.getName();
}

After a GraphQL service is running (typically at a URL on a web service), it can receive GraphQL queries to validate and execute. The service first checks a query to ensure it only refers to the types and fields defined, and then runs the provided functions to produce a result.

For example, the query:

{
  me {
    name
  }
}

Could produce the following JSON result:

{
  "me": {
    "name": "Luke Skywalker"
  }
}

The GraphiQL tool

GraphiQL is the GraphQL integrated development environment (IDE). It offers syntax highlighting, intellisense auto-completion, automatic documentation, and much more.

Check out the github repo here and get the npm package from here.

Find and online implementation here: https://lucasconstantino.github.io/graphiql-online/ – update the endpoint to https://gitlab.com/api/graphql and try the below query.

query {
  project(fullPath: "gitlab-org/graphql-sandbox") {
    name
    issue(iid: "2") {
      title
    }
  }
}

Additional Reading

, , ,

Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *