什么时API
API的本质就是帮人读数据、写数据。流派在变,技术在变,写API、用API的人的职称也会变,但是API的本质不会变。无论是哪种API,它的终极目的就是能让人读数据读的轻松,写数据写的愉快。懂了这个,就明白了GraphQL解决的是什么问题。
为什么不用REST
- Rest一次只能请求一个资源,会造成太多的http请求
- Rest的版本控制问题是一个痛
GraphQL的关键语句
- query:查询,相当于GET
- mutation:变化,相当于POST, PUT, DELETE
环境搭建
- win10
- Python3.6
- pip install django==2.0.1
- pip install graphene-django==2.0.0
创建项目
- django-admin.py startproject django_graphql
- cd django_graphql
- python startapp book
- 项目的文件组织
创建model
- book/models.py
from django.db import models
# Create your models here.
class Title(models.Model):
title = models.CharField(max_length=255, verbose_name="标题")
def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=255, verbose_name="作者姓名")
def __str__(self):
return self.name
class Book(models.Model):
title = models.ForeignKey(Title, related_name='book_title', on_delete=models.CASCADE)
author = models.ForeignKey(Author, related_name='book_author', on_delete=models.CASCADE)
创建schema.py
- book/schema.py
import graphene
from graphene_django.types import DjangoObjectType
from .models import Book, Title, Author
class BookType(DjangoObjectType):
class Meta:
model = Book
class TitleType(DjangoObjectType):
class Meta:
model = Title
class AuthorType(DjangoObjectType):
class Meta:
model = Author
# 定义动作,类似POST, PUT, DELETE
class BookInput(graphene.InputObjectType):
title = graphene.String(required=True)
author = graphene.String(required=True)
class CreateBook(graphene.Mutation):
# api的输入参数
class Arguments:
book_data = BookInput(required=True)
# api的响应参数
ok = graphene.Boolean()
book = graphene.Field(BookType)
# api的相应操作,这里是create
def mutate(self, info, book_data):
title = Title.objects.create(title=book_data['title'])
author = Author.objects.create(name=book_data['author'])
book = Book.objects.create(title=title, author=author)
ok = True
return CreateBook(book=book, ok=ok)
# 定义查询,类似GET
class Query(object):
all_books = graphene.List(BookType)
all_titles = graphene.List(TitleType)
all_authors = graphene.List(AuthorType)
def resolve_all_books(self, info, **kwargs):
# 查询所有book的逻辑
return Book.objects.all()
def resolve_all_titles(self, info, **kwargs):
# 查询所有title的逻辑
return Book.objects.select_related('book_title').all()
def resolve_all_authors(self, info, **kwargs):
# 查询所有author的逻辑
return Book.objects.select_related('book_author').all()
创建总的schema入口文件
- 再settings.py的同级目录下创建:schema.py
import graphene
import book.schema
class Query(book.schema.Query, graphene.ObjectType):
# 总的Schema的query入口
pass
class Mutations(graphene.ObjectType):
# 总的Schema的mutations入口
create_book = book.schema.CreateBook.Field()
schema = graphene.Schema(query=Query, mutation=Mutations)
配置总的url
from django.contrib import admin
from django.urls import path
from graphene_django.views import GraphQLView
from .schema import schema
urlpatterns = [
path('admin/', admin.site.urls),
path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)),
]
启动项目
- python manage.py makemigrations
- python manage.py migrate
- python manage.py runserver 0.0.0.0:8080
-
访问:localhost:8080/graphql/
创建book
mutation createBook {
createBook(bookData: {title:"django-graphgl2", author: "ns2250225"}) {
book {
title {
id,
title
},
author {
id,
name
}
}
ok
}
}