2018-10-18 13:45:18 +00:00
|
|
|
|
|
|
|
Starlette includes optional support for GraphQL, using the `graphene` library.
|
|
|
|
|
|
|
|
Here's an example of integrating the support into your application.
|
|
|
|
|
|
|
|
```python
|
|
|
|
from starlette.applications import Starlette
|
2018-11-01 12:52:16 +00:00
|
|
|
from starlette.graphql import GraphQLApp
|
2018-10-18 13:45:18 +00:00
|
|
|
import graphene
|
|
|
|
|
|
|
|
|
|
|
|
class Query(graphene.ObjectType):
|
|
|
|
hello = graphene.String(name=graphene.String(default_value="stranger"))
|
|
|
|
|
|
|
|
def resolve_hello(self, info, name):
|
|
|
|
return "Hello " + name
|
|
|
|
|
|
|
|
|
|
|
|
app = Starlette()
|
2018-11-01 12:52:16 +00:00
|
|
|
app.add_route('/', GraphQLApp(schema=graphene.Schema(query=Query)))
|
2018-10-18 13:45:18 +00:00
|
|
|
```
|
|
|
|
|
2018-10-18 15:58:49 +00:00
|
|
|
If you load up the page in a browser, you'll be served the GraphiQL tool,
|
|
|
|
which you can use to interact with your GraphQL API.
|
|
|
|
|
|
|
|
![GraphiQL](img/graphiql.png)
|
|
|
|
|
2018-10-18 13:45:18 +00:00
|
|
|
## Sync or Async executors
|
|
|
|
|
|
|
|
If you're working with a standard ORM, then just use regular function calls for
|
|
|
|
your "resolve" methods, and Starlette will manage running the GraphQL query within a
|
|
|
|
seperate thread.
|
|
|
|
|
|
|
|
If you want to use an asyncronous ORM, then use "async resolve" methods, and
|
2018-10-18 15:58:49 +00:00
|
|
|
make sure to setup Graphene's AsyncioExecutor using the `executor` argument.
|
2018-10-18 13:45:18 +00:00
|
|
|
|
|
|
|
```python
|
|
|
|
from graphql.execution.executors.asyncio import AsyncioExecutor
|
|
|
|
from starlette.applications import Starlette
|
|
|
|
import graphene
|
|
|
|
|
|
|
|
|
|
|
|
class Query(graphene.ObjectType):
|
|
|
|
hello = graphene.String(name=graphene.String(default_value="stranger"))
|
|
|
|
|
|
|
|
async def resolve_hello(self, info, name):
|
|
|
|
# We can make asynchronous network calls here.
|
|
|
|
return "Hello " + name
|
|
|
|
|
|
|
|
|
|
|
|
app = Starlette()
|
2018-10-18 15:58:49 +00:00
|
|
|
|
|
|
|
# We're using `executor=AsyncioExecutor()` here.
|
2018-11-10 08:02:51 +00:00
|
|
|
app.add_route('/', GraphQLApp(schema=graphene.Schema(query=Query), executor=AsyncioExecutor()))
|
2018-10-18 13:45:18 +00:00
|
|
|
```
|