Skip to main content

Tools for GraphQL client in python.

Project description

GRAPHQL2PYTHON

Tools for GraphQL client in python.

Installation

Install using

pip install graphql2python

A Simple Example for Query

For the query

query HeroForEpisode($ep: Episode!) {
  hero(episode: $ep) {
    name
    ... on Droid {
      primaryFunction
    }
    ... on Human {
      height
    }
  }
}

we have

from graphql2python.query import InlineFragment, Operation, Query, Variable, Argument

var_ep = Variable(name="ep", type="Episode!")
arg_episode = Argument(name="episode", value=var_ep)

hero = Query(
    name="hero",
    arguments=[arg_episode],
    fields=[
        "name",
        InlineFragment(type="Droid", fields=["primaryFunction"]),
        InlineFragment(type="Human", fields=["height"]),
    ]
)

operation = Operation(
    type="query",
    name="HeroForEpisode",
    queries=[hero],
    variables=[var_ep]
)
operation.render()
# query HeroForEpisode(
#   $ep: Episode!
# ) {
#   hero(
#     episode: $ep
#   ) {
#     name
#     ... on Droid {
#       primaryFunction
#     }
#     ... on Human {
#       height
#     }
#   }
# }

A simple Example for Model

Run

graphql2python render --config ./graphql2python.yaml

where

# graphql2python.yaml
schema: ./schema.graphql
output: ./model.py

and

# schema.graphql
interface Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
}

type Human implements Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
  starships: [Starship]
  totalCredits: Int
}

type Starship {
  id: ID!
  name: String!
  length: Float
}

type Droid implements Character {
  id: ID!
  name: String!
  friends: [Character]
  appearsIn: [Episode]!
  primaryFunction: String
}

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

we have in model.py:

"""Auto-generated by graphql2python."""

# pylint: disable-all
# mypy: ignore-errors

import enum
from datetime import date, datetime
from typing import Any, List, Literal, Optional, Union

from pydantic import BaseModel, Field

__all__ = [
    "GraphQLBaseModel",
    # scalars
    "Boolean",
    "Float",
    "ID",
    "Int",
    "String",
    # enums
    "Episode",
    # unions
    # interfaces
    "Character",
    # objects
    "Droid",
    "Human",
    "Starship",
]


class GraphQLBaseModel(BaseModel):
    """Base Model for GraphQL object."""

    class Config:
        allow_population_by_field_name = True
        json_encoders = {
            # custom output conversion for datetime
            datetime: lambda dt: dt.isoformat()
        }
        smart_union = True


# The `Boolean` scalar type represents `true` or `false`.
Boolean = str


# The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE
# 754](https://en.wikipedia.org/wiki/IEEE_floating_point).
Float = str


# The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID
# type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an
# input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.
ID = str


# The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31)
# and 2^31 - 1.
Int = str


# The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most
# often used by GraphQL to represent free-form human-readable text.
String = str


class Episode(enum.Enum):
    """
    An Enum type
    See https://graphql.org/learn/schema/#enumeration-types
    """
    EMPIRE = "EMPIRE"
    JEDI = "JEDI"
    NEWHOPE = "NEWHOPE"


class Character(GraphQLBaseModel):
    """
    An Interface type
    See https://graphql.org/learn/schema/#interfaces
    """
    appearsIn: List[Optional['Episode']]
    id: 'ID'
    name: 'String'
    friends: Optional[List[Optional['Character']]] = Field(default_factory=list)


class Droid(
    Character,
):
    """
    An Object type
    See https://graphql.org/learn/schema/#object-types-and-fields
    """
    primaryFunction: Optional['String'] = Field(default=None)


class Human(
    Character,
):
    """
    An Object type
    See https://graphql.org/learn/schema/#object-types-and-fields
    """
    starships: Optional[List[Optional['Starship']]] = Field(default_factory=list)
    totalCredits: Optional['Int'] = Field(default=None)


class Starship(GraphQLBaseModel):
    """
    An Object type
    See https://graphql.org/learn/schema/#object-types-and-fields
    """
    id: 'ID'
    name: 'String'
    length: Optional['Float'] = Field(default=None)

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

graphql2python-0.0.2-py3-none-any.whl (22.1 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