graphene/README.md

102 lines
2.3 KiB
Markdown
Raw Normal View History

2015-09-26 10:07:01 +03:00
# Graphene: Python DSL for GraphQL
2015-09-24 12:11:50 +03:00
This is a library to use GraphQL in Python in a easy way.
It will map the models/fields to internal GraphQL-py objects without effort.
[![Build Status](https://travis-ci.org/syrusakbary/graphene.svg?branch=master)](https://travis-ci.org/syrusakbary/graphene)
[![Coverage Status](https://coveralls.io/repos/syrusakbary/graphene/badge.svg?branch=master&service=github)](https://coveralls.io/github/syrusakbary/graphene?branch=master)
2015-09-24 12:17:56 +03:00
## Usage
Example code of a GraphQL schema using Graphene:
### Schema definition
```python
import graphene
# ...
class Character(graphene.Interface):
id = graphene.IDField()
name = graphene.StringField()
2015-09-24 12:26:57 +03:00
friends = graphene.ListField('self')
2015-09-24 12:17:56 +03:00
def resolve_friends(self, args, *_):
return [Human(f) for f in self.instance.friends]
2015-09-24 12:17:56 +03:00
class Human(Character):
homePlanet = graphene.StringField()
class Query(graphene.ObjectType):
human = graphene.Field(Human)
2015-09-24 12:17:56 +03:00
schema = graphene.Schema(query=Query)
2015-09-24 12:17:56 +03:00
```
### Querying
Querying `graphene.Schema` is as simple as:
```python
query = '''
query HeroNameQuery {
hero {
name
}
}
'''
result = schema.execute(query)
2015-09-24 12:17:56 +03:00
```
2015-09-26 09:31:53 +03:00
### Relay Schema
Graphene also supports Relay, check the (Starwars Relay example)[tests/starwars_relay]!
2015-09-26 09:31:53 +03:00
```python
class Ship(relay.Node):
'''A ship in the Star Wars saga'''
name = graphene.StringField(description='The name of the ship.')
@classmethod
def get_node(cls, id):
2015-09-28 06:37:47 +03:00
return Ship(getShip(id))
2015-09-26 09:31:53 +03:00
class Query(graphene.ObjectType):
ships = relay.ConnectionField(Ship, description='The ships used by the faction.')
2015-09-26 09:31:53 +03:00
node = relay.NodeField()
@resolve_only_args
def resolve_ships(self):
return [Ship(s) for s in getShips()]
2015-09-26 09:31:53 +03:00
```
2015-09-26 09:31:53 +03:00
### Django+Relay Schema
2015-09-26 09:31:53 +03:00
Graphene also supports Relay, check the (Starwars Django example)[tests/starwars_django]!
2015-09-26 09:31:53 +03:00
```python
class Ship(DjangoNode):
class Meta:
model = YourDjangoModelHere
# only_fields = ('id', 'name') # Only map this fields from the model
2015-09-26 09:31:53 +03:00
class Query(graphene.ObjectType):
node = relay.NodeField()
2015-09-26 09:31:53 +03:00
```
2015-09-24 12:11:50 +03:00
## Contributing
After cloning this repo, ensure dependencies are installed by running:
```sh
python setup.py install
```
After developing, the full test suite can be evaluated by running:
```sh
python setup.py test # Use --pytest-args="-v -s" for verbose mode
```