Uncategorized

Creating API with GraphQL+Django

Environment:

Django 1.10.4
graphene-django-1.2.0

Setup

Install graphene-django,migrate and createsuperuser if it’s a new Django project:

Edit settings.py,add graphene-django to INSTALLED_APPS

Then editurls.py,import GraphQLView

Execute runserver then open uri /graphql, will reponse a error about schema。

Schema

Create schema.py, folder structure like blow:

Edit schema.py, import DjangoObjectType and graphene. Use Django’s User Model as example:

Edit settings.py:

Now reopen /graphql will show GraphiQL (GraphQL Web IDE), wirte then query:

Return username and email of admin when click button (▶️). More detail query language of GraphQL see :http://graphql.org/learn/queries/

Schema & Type & Field

The query language is the same whether your backend using Python or Nodejs. Schema defines the presentation structure of the data, including various Types, where Query and Mutation are two special types, and Type specifies the returned data field through Fields. Taking the previous code as an example, Type(Query) and Fields(users) are defined in the code, and resolve is specified to process the data.

Filter

Insert a new user for testing:

Editschema.py

Run the new query lanaguage:

Mutation

Extend graphene.Mutation:

Query lanaguage declare as mutation, define fields of response:

Reponse:

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of