Skip to main content

Starlette ASGI adapter for Tartiflette

Project description

tartiflette-starlette

travis black python pypi license

Starlette-powered ASGI adapter for Tartiflette, the Python asynchronous GraphQL engine.

⚠️ This package is still under development. Be sure to pin your dependencies!

Installation

Assuming you have already installed Tartiflette, you can install tartiflette-starlette from PyPI:

pip install tartiflette-starlette

Note: tartiflette-starlette is compatible with Starlette 0.12+.

Usage

Getting started with Tartiflette or GraphQL? See Resources.

The TartifletteApp class provided by tartiflette-starlette is an ASGI3-compliant application. As such, it can be served on its own using any ASGI web server, or it can be mounted onto another ASGI application.

Note: GraphQL subscriptions are not supported yet.

Creating a GraphQL app

The following example defines a standalone TartifletteApp which exposes the GraphQL endpoint at /graphql:

# graphql.py
from tartiflette import Resolver

from tartiflette_starlette import TartifletteApp

# Create a Tartiflette resolver for the `hello` field.
@Resolver("Query.hello")
async def resolve_hello(parent, args, context, info):
    name = args["name"]
    return f"Hello, {name}!"

# Define the schema using an SDL string.
# Note: Tartiflette also has support for `.graphql` files.
# See: https://tartiflette.io/docs/api/engine
sdl = """
    type Query {
        hello(name: String): String
    }
"""

app = TartifletteApp(sdl=sdl, path="/graphql")

Serving the app

Since TartifletteApp is an ASGI application, it can be served using any ASGI web server, e.g. uvicorn:

uvicorn graphql:app

Making GraphQL queries

Once the server is running, we're ready to make queries.

As per the GraphQL spec, the query can be passed in various ways:

  • URL query string (methods: GET, POST):
curl 'http://localhost:8000/graphql?query=\{hello(name:"Chuck")\}'
  • JSON-encoded body (methods: POST):
curl \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"query": "{ hello(name: \"Chuck\") }"}' \
  http://localhost:8000/graphql
  • Raw body (methods: POST):
curl \
  -X POST \
  -H "Content-Type: application/graphql" \
  -d '{ hello(name: "Chuck") }' \
  http://localhost:8000/graphql

All these requests result in the same response:

{
  "data": { "hello": "Hello, Chuck!" },
  "errors": null
}

Furthermore, you can use the built-in GraphiQL client: visit http://localhost:8000/graphql to interactively make queries in the browser. ✨

Mouting onto an ASGI application

Most async web frameworks provide a way to add a route to another ASGI application. This allows you to serve a TartifletteApp along with other endpoints.

The following example mounts the GraphQL app from Creating a GraphQL app onto a Starlette application:

# main.py
from starlette.applications import Starlette
from graphql import app as graphql_app

app = Starlette()
app.mount("/", graphql_app)

You can serve it using uvicorn main:app and make requests at http://localhost:8000/graphql.

Accessing request information

The Starlette Request object is made available in the Tartiflette context which, for example, you can access from resolvers:

@Resolver("Query.whoami")
async def resolve_whoami(parent, args, context, info) -> str:
    request = context["request"]
    user = getattr(request.state, "user", None)
    return "a mystery" if user is None else user

Resources

Once a TartifletteApp is setup, it's just Tartiflette and GraphQL from there!

Here are a few resources you may find useful when getting started:

Happy querying!

API Reference

tartiflette_starlette.TartifletteApp

Parameters

Note: all parameters are keyword-only.

  • engine (Engine): a Tartiflette engine. Required if sdl is not given.
  • sdl (str): a GraphQL schema defined using the GraphQL Schema Definition Language. Required if engine is not given.
  • graphiql (bool): whether to serve the GraphiQL when accessing the endpoint via a web browser. Defaults to True.
  • path (str): the path which clients should make GraphQL queries to. Defaults to "/". A popular alternative is "/graphql".
  • schema_name (str): name of the GraphQL schema from the Schema Registry which should be used — mostly for advanced usage. Defaults to "default".

Methods

  • __call__(scope, receive, send): implementation of the ASGI3 callable interface.

Error responses

Status code Description
405 Method Not Allowed The HTTP method is not one of GET, HEAD or POST.
415 Unsupported Media Type A POST request was made with an unsupported media type.
400 Bad Request The GraphQL query could not be found in the request data.

Contributing

Want to contribute? Awesome! Be sure to read our Contributing guidelines.

Changelog

Changes to this project are recorded in the changelog.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tartiflette-starlette-0.1.1.tar.gz (9.6 kB view hashes)

Uploaded Source

Built Distribution

tartiflette_starlette-0.1.1-py3-none-any.whl (9.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page