2019-04-26 18:48:37 +03:00
Installation
============
Graphene-Django takes a few seconds to install and set up.
Requirements
------------
Graphene-Django currently supports the following versions of Django:
2020-05-09 14:13:47 +03:00
* >= Django 2.2
2019-04-26 18:48:37 +03:00
Installation
------------
.. code :: bash
pip install graphene-django
**We strongly recommend pinning against a specific version of Graphene-Django because new versions could introduce breaking changes to your project.**
Add `` graphene_django `` to the `` INSTALLED_APPS `` in the `` settings.py `` file of your Django project:
.. code :: python
INSTALLED_APPS = [
...
2020-08-05 22:17:53 +03:00
"django.contrib.staticfiles", # Required for GraphiQL
"graphene_django"
2019-04-26 18:48:37 +03:00
]
2019-05-13 10:01:44 +03:00
We need to add a `` graphql `` URL to the `` urls.py `` of your Django project:
2019-04-26 18:48:37 +03:00
2020-05-09 14:13:47 +03:00
For Django 2.2 and above:
2020-03-07 19:17:45 +03:00
2019-04-26 18:48:37 +03:00
.. code :: python
2019-05-13 10:01:44 +03:00
from django.urls import path
2019-04-26 18:48:37 +03:00
from graphene_django.views import GraphQLView
urlpatterns = [
# ...
2019-05-13 10:01:44 +03:00
path("graphql", GraphQLView.as_view(graphiql=True)),
2019-04-26 18:48:37 +03:00
]
(Change `` graphiql=True `` to `` graphiql=False `` if you do not want to use the GraphiQL API browser.)
Finally, define the schema location for Graphene in the `` settings.py `` file of your Django project:
.. code :: python
GRAPHENE = {
2020-08-05 22:17:53 +03:00
"SCHEMA": "django_root.schema.schema"
2019-04-26 18:48:37 +03:00
}
Where `` path.schema.schema `` is the location of the `` Schema `` object in your Django project.
The most basic `` schema.py `` looks like this:
.. code :: python
import graphene
class Query(graphene.ObjectType):
2020-08-05 22:17:53 +03:00
hello = graphene.String(default_value="Hi!")
2019-04-26 18:48:37 +03:00
schema = graphene.Schema(query=Query)
2020-01-11 16:49:17 +03:00
To learn how to extend the schema object for your project, read the basic tutorial.
CSRF exempt
-----------
2020-12-31 02:37:57 +03:00
If you have enabled `CSRF protection <https://docs.djangoproject.com/en/3.0/ref/csrf/> `_ in your Django app
2020-01-11 16:49:17 +03:00
you will find that it prevents your API clients from POSTing to the `` graphql `` endpoint. You can either
update your API client to pass the CSRF token with each request (the Django docs have a guide on how to do that: https://docs.djangoproject.com/en/3.0/ref/csrf/#ajax) or you can exempt your Graphql endpoint from CSRF protection by wrapping the `` GraphQLView `` with the `` csrf_exempt ``
decorator:
.. code :: python
# urls.py
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
urlpatterns = [
# ...
path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True))),
]