|
| 1 | +--- |
| 2 | +name: Django Graphbox |
| 3 | +description: Package for easy building a GraphQL API with basic CRUD operations for Django models. |
| 4 | +url: https://90horasporsemana.com/graphbox/ |
| 5 | +github: yefeza/django-graphbox |
| 6 | +--- |
| 7 | + |
| 8 | +A Quickstart for Django Graphbox: |
| 9 | + |
| 10 | +1. Install the package: |
| 11 | + |
| 12 | +```bash |
| 13 | +pip install django-graphbox |
| 14 | +``` |
| 15 | + |
| 16 | +2. Create a new Django project: |
| 17 | + |
| 18 | +```bash |
| 19 | +django-admin startproject myproject |
| 20 | +``` |
| 21 | + |
| 22 | +3. Create a new Django app: |
| 23 | + |
| 24 | +```bash |
| 25 | +cd myproject |
| 26 | +python manage.py startapp myapp |
| 27 | +``` |
| 28 | + |
| 29 | +4. Define your Django models in `myapp/models.py`: |
| 30 | + |
| 31 | +```python |
| 32 | +from django.db import models |
| 33 | + |
| 34 | +class MyModel(models.Model): |
| 35 | + name = models.CharField(max_length=100) |
| 36 | +``` |
| 37 | + |
| 38 | +5. Create and run migrations: |
| 39 | + |
| 40 | +```bash |
| 41 | +python manage.py makemigrations |
| 42 | +python manage.py migrate |
| 43 | +``` |
| 44 | + |
| 45 | +6. Configure and Build your GraphQL Schema in `myapp/schema.py`: |
| 46 | + |
| 47 | +```python |
| 48 | +from django_graphbox.builder import SchemaBuilder |
| 49 | +from myapp.models import MyModel |
| 50 | + |
| 51 | +builder = SchemaBuilder() |
| 52 | +builder.add_model(MyModel) |
| 53 | + |
| 54 | +query_class = builder.build_schema_query() |
| 55 | +mutation_class = builder.build_schema_mutation() |
| 56 | +``` |
| 57 | + |
| 58 | +7. Create a main Schema in `myproject/schema.py` (In this main schema you can add your own queries and mutations): |
| 59 | + |
| 60 | +```python |
| 61 | +import graphene |
| 62 | +from myapp.schema import query_class, mutation_class |
| 63 | + |
| 64 | +class Query(query_class, graphene.ObjectType): |
| 65 | + pass |
| 66 | + |
| 67 | +class Mutation(mutation_class, graphene.ObjectType): |
| 68 | + pass |
| 69 | + |
| 70 | +schema = graphene.Schema(query=Query, mutation=Mutation) |
| 71 | +``` |
| 72 | + |
| 73 | +8. Add the GraphQL view to your `myproject/urls.py`: |
| 74 | + |
| 75 | +```python |
| 76 | +from django.urls import path |
| 77 | +from graphene_file_upload.django import FileUploadGraphQLView |
| 78 | +from django.views.decorators.csrf import csrf_exempt |
| 79 | +from myproject.schema import schema |
| 80 | + |
| 81 | +urlpatterns = [ |
| 82 | + path('graphql/', csrf_exempt(FileUploadGraphQLView.as_view(graphiql=True, schema=schema))), |
| 83 | +] |
| 84 | +``` |
| 85 | + |
| 86 | +9. Run the server: |
| 87 | + |
| 88 | +```bash |
| 89 | +python manage.py runserver |
| 90 | +``` |
| 91 | + |
| 92 | +10. Open the GraphiQL interface at `http://localhost:8000/graphql/` and start querying your API! |
| 93 | + |
| 94 | +You can find advanced examples with authentication, filters, validations and more on github or pypi. |
0 commit comments