#graphql

why it exist?
from someone who has uses REST API previously,

I get the idea, I get the background.
your data is directly your API. it’s like you’re just defining the classes.

there are graphQL specific things, that are new.

first,

nonNull

source
I’m going to use graphene as an example here. it’s python, so it has good amount of abstraction so that we can focus on graphQL itself.

if we check the type documentation, it will show itself as exclamation mark.

type Character{
	name!
}

guess what the schema for this piece of code?

from graphene import ObjectType, String, Field
 
  
 
class Person(ObjectType):
 
	full_name = String()
 
	first_name = graphene.NonNull(String)
 
	last_name = graphene.NonNull(String)
 
  
 
def resolve_full_name(parent, info):
 
	return f"{parent.first_name} {parent.last_name}"
 
  
 
class Query(ObjectType):
	me = Field(Person)
 
	def resolve_me(parent, info):
		# returns an object that represents a Person
		# return a person named "John Doe"
 
		return Person(first_name="John", last_name="Doe")
 
  
 
schema = graphene.Schema(query=Query)

note about graphene:

  • parent means this. maybe you’re more accustomed to that variable name (I do)
  • graphene auto create field based on class attribute
  • graphene auto pair resolver with attribute based on the name of the function (resolver_attribute)

here’s the answer!

what does nonNull mean?

it means that you the server (and you) expect those value to be not null. doesn’t mean you have to ask that data! You can ask firstNameor not, up to you. But if you do, it will have string data in it (not null)

passing parameter

analogue to ‘get me the data of a person with this ID’,

here’s how the query is going to look like

query {
    human(name: "Luke Skywalker") {
        firstName
        lastName
    }
}

here’s an example code

  
 
from graphene import ObjectType, String, Field
 
  
 
class Person(ObjectType):
	full_name = String()
	first_name = graphene.NonNull(String)
	last_name = graphene.NonNull(String)
 
  
 
def resolve_full_name(parent, info):
	return f"{parent.first_name} {parent.last_name}"
 
  
 
class Query(ObjectType):
	human = Field(Person, name=String(required=True)) # <-- this is the new line
 
  
 
def resolve_human(parent, info, name): # <-- notice the new argument
	# returns an object that represents a Person
	# return a person named "John Doe"
	return Person(first_name="John", last_name="Doe")
 
 
schema = graphene.Schema(query=Query)

in graphene, it will automatically add the name as function’s argument(or parameter?)

note:

A parameter is a variable in a function definition. It is a placeholder and hence does not have a concrete value. An argument is a value passed during function invocation.

source