MGE-GraphQL is a Python library for building GraphQL mutations fast and easily

Related tags

GraphQLmge-graphql
Overview

MGE-GraphQL Logo

MGE-GraphQL PyPI version Documentation Status

Introduction

MGE-GraphQL is a Python library for building GraphQL mutations fast and easily.

  • Data Validations: A similar data validation workflow as Django.
  • Errors: Support for throwing errors
  • Permissions: Support for user permissions

Installation

For instaling MGE-GraphQL, just run this command in your shell

pip install "mge-graphql"

Examples

Here is one example for you to get started: Create error_codes.py and define some errors

from enum import Enum
from mge_graphql.utils.error_codes import (
    MGE_ERROR_CODE_ENUMS,
    generate_error_codes
)


class AccountErrorCode(Enum):
    # Here you define your Error Codes
    INVALID_PASSWORD = "invalid_password"

# Register error codes
MGE_ERROR_CODE_ENUMS.append(AccountErrorCode)
generate_error_codes()

Create enums.py to define your Graphene Error Enums

import graphene
import error_codes as account_error_codes

# Create Graphene Enum
AccountErrorCode = graphene.Enum.from_enum(account_error_codes.AccountErrorCode)

Create types.py to create your custom error graphql object type

from mge_graphql.types.common import Error
from enums import AccountErrorCode

class AccountError(Error):
    # Custom fields
    # Support for error_code
    code = AccountErrorCode(description="The error code.", required=True)

Create mutations.py to create your first mutation

from mge_graphql.mutations.base import BaseMutation
from mge_graphql.exceptions import ValidationError
from enums import AccountErrorCode
from types import AccountError
import graphene

class AccountRegister(BaseMutation):
    # YOUR GRAPHENE FIELDS
    username = graphene.String(required=True)
    password = graphene.String(required=True)

    class Arguments:
        username = graphene.String(required=True)
        password = graphene.String(required=True)

    class Meta:
        description = "Register a new account."
        # Set our custom AccountError class
        error_type_class = AccountError

    @classmethod
    def clean_password(cls, password, errors):
        if len(password) < 6:
            errors["password"].append(
                ValidationError(
                    {
                        "password": ValidationError(
                            "Password cannot be less than 6 characters.",
                            code=AccountErrorCode.INVALID_PASSWORD
                        )
                    }
                )
            )

        return password

    @classmethod
    def clean(cls, **data):
        errors = defaultdict(list)
        cls.clean_password(data["password"], errors)

        if errors:
            raise ValidationError(errors)

        return data
    
    @classmethod
    def check_permissions(cls, context):
        # Permission Checks. 
        # If False, then it will raise an Permission Denied Error
        return True

    @classmethod
    def perform_mutation(cls, _root, info, **data):
        cleaned_data = cls.clean(**data)
        
        cleaned_username = cleaned_data.get("username")
        cleaned_password = cleaned_data.get("password")

        # User Save // Any Mutation Logic

        return AccountRegister(
            username=cleaned_username, 
            password=cleaned_password
        )

Create schema.py and register your mutation:

from mutations import AccountRegister
import graphene

class Mutation(graphene.ObjectType):
    account_register = AccountRegister.Field()


schema = graphene.Schema(mutation=Mutation)

And.. we are done! Let's try our mutation

invalid input:

mutation {
  accountRegister(username: "test", password: "234") {
    username
    password
    
    errors {
      field
      message
      code
    }
  }
}
{
  "data": {
    "accountRegister": {
      "username": null,
      "password": null,
      "errors": [
        {
          "field": "password",
          "message": "Password cannot be less than 6 characters.",
          "code": "INVALID_PASSWORD"
        }
      ]
    }
  }
}

valid input:

mutation {
  accountRegister(username: "test", password: "123456") {
    username
    password
    
    errors {
      field
      message
      code
    }
  }
}
{
  "data": {
    "accountRegister": {
      "username": "test",
      "password": "123456",
      "errors": []
    }
  }
}

If method check_permissions returns False:

mutation {
  accountRegister(username: "test", password: "123456") {
    username
    password
    
    errors {
      field
      message
      code
    }
  }
}
{
  "data": {
    "accountRegister": {
      "username": null,
      "password": null,
      "errors": [
        {
          "field": null,
          "message": "You do not have permission to perform this action",
          "code": "PERMISSION_DENIED"
        }
      ]
    }
  }
}

Documentation

Documentation and links to additional resources are available at https://mge-graphql.readthedocs.io/

You might also like...
GraphQL framework for Python

Graphene 💬 Join the community on Slack We are looking for contributors! Please check the ROADMAP to see how you can help ❤️ The below readme is the d

GraphQL Engine built with Python 3.6+ / asyncio
GraphQL Engine built with Python 3.6+ / asyncio

Tartiflette is a GraphQL Server implementation built with Python 3.6+. Summary Motivation Status Usage Installation Installation dependencies Tartifle

A python graphql api, which serves ECB currency rates from last 90 days.
A python graphql api, which serves ECB currency rates from last 90 days.

Exchange Rate Api using GraphQL Get Code git pull https://github.com/alaturqua/exchangerate-graphql.git Create .env file with following content and s

This is a simple Python that will parse instanceStats GraphQL Query into a CSV
This is a simple Python that will parse instanceStats GraphQL Query into a CSV

GraphQL Python Labs - by Gabs the CSE Table of Contents About The Project Getting Started Prerequisites Installation and Usage Roadmap Contributing Li

Pygitstats - a package that allows you to use the GitHub GraphQL API with ease in your Python programs

Pygitstats - a package that allows you to use the GitHub GraphQL API with ease in your Python programs

GraphQL is a query language and execution engine tied to any backend service.

GraphQL The GraphQL specification is edited in the markdown files found in /spec the latest release of which is published at https://graphql.github.io

Django registration and authentication with GraphQL.
Django registration and authentication with GraphQL.

Django GraphQL Auth Django registration and authentication with GraphQL. Demo About Abstract all the basic logic of handling user accounts out of your

Django Project with Rest and Graphql API's

Django-Rest-and-Graphql # 1. Django Project Setup With virtual environment: mkdir {project_name}. To install virtual Environment sudo apt-get install

Generate a FullStack Playground using GraphQL and FastAPI 🚀

FastQL - FastAPI GraphQL Playground Generate a FullStack playground using FastAPI and GraphQL and Ariadne 🚀 . This Repository is based on this Articl

Releases(v1.1.0)
Owner
MGE Software
We build enterprise applications
MGE Software
GraphQL framework for Python

Graphene 💬 Join the community on Slack We are looking for contributors! Please check the ROADMAP to see how you can help ❤️ The below readme is the d

GraphQL Python 7.5k Jan 01, 2023
Burp Suite extension to log GraphQL operations as a comment

Burp GraphQL Logger A very simple, straightforward extension that logs GraphQL operations as a comment in the Proxy view. To enable the highlight, unc

22 Jul 02, 2022
Integrate GraphQL into your Django project.

Graphene-Django A Django integration for Graphene. 💬 Join the community on Slack Documentation Visit the documentation to get started! Quickstart For

GraphQL Python 4k Dec 31, 2022
Ariadne is a Python library for implementing GraphQL servers using schema-first approach.

Ariadne Ariadne is a Python library for implementing GraphQL servers. Schema-first: Ariadne enables Python developers to use schema-first approach to

Mirumee Labs 1.9k Jan 01, 2023
A Python 3.6+ port of the GraphQL.js reference implementation of GraphQL.

GraphQL-core 3 GraphQL-core 3 is a Python 3.6+ port of GraphQL.js, the JavaScript reference implementation for GraphQL, a query language for APIs crea

GraphQL Python 458 Dec 13, 2022
Graphql-codegen library - a pure python implementation

turms DEVELOPMENT Inspiration Turms is a pure python implementation of the awesome graphql-codegen library, following a simliar extensible design. It

Johannes Roos 22 Dec 23, 2022
This is a simple Python that will parse instanceStats GraphQL Query into a CSV

GraphQL Python Labs - by Gabs the CSE Table of Contents About The Project Getting Started Prerequisites Installation and Usage Roadmap Contributing Li

Gabriel (Gabs) Cerioni 1 Oct 27, 2021
Pygitstats - a package that allows you to use the GitHub GraphQL API with ease in your Python programs

Pygitstats - a package that allows you to use the GitHub GraphQL API with ease in your Python programs

Dillon Barnes 4 Mar 29, 2022
Lavrigon - A Python Webservice to check the status of any given local service via a REST call

lavrigon A Python Webservice to check the status of any given local service via

3 Jan 02, 2022
Graphene MongoEngine integration

Graphene-Mongo A Mongoengine integration for Graphene. Installation For installing graphene-mongo, just run this command in your shell pip install gra

GraphQL Python 261 Dec 31, 2022
graphw00f is Server Engine Fingerprinting utility for software security professionals looking to learn more about what technology is behind a given GraphQL endpoint.

graphw00f - GraphQL Server Fingerprinting graphw00f (inspired by wafw00f) is the GraphQL fingerprinting tool for GQL endpoints. Table of Contents How

Dolev Farhi 282 Jan 04, 2023
tartiflette-aiohttp is a wrapper of aiohttp which includes the Tartiflette GraphQL Engine, do not hesitate to take a look of the Tartiflette project.

tartiflette-aiohttp is a wrapper of aiohttp which includes the Tartiflette GraphQL Engine. You can take a look at the Tartiflette API documentation. U

tartiflette 60 Nov 08, 2022
(Now finding maintainer) 🐍A Pythonic way to provide JWT authentication for Flask-GraphQL

Flask-GraphQL-Auth What is Flask-GraphQL-Auth? Flask-GraphQL-Auth is JWT decorator for flask-graphql inspired from Flask-JWT-Extended. all you have to

Seonghyeon Kim 64 Feb 19, 2022
Django Project with Rest and Graphql API's

Django-Rest-and-Graphql # 1. Django Project Setup With virtual environment: mkdir {project_name}. To install virtual Environment sudo apt-get install

Shubham Agrawal 5 Nov 22, 2022
Tyk Open Source API Gateway written in Go, supporting REST, GraphQL, TCP and gRPC protocols

Tyk API Gateway Tyk is an open source Enterprise API Gateway, supporting REST, GraphQL, TCP and gRPC protocols. Tyk Gateway is provided ‘Batteries-inc

Tyk Technologies 8k Jan 09, 2023
Lightning fast and portable programming language!

Photon Documentation in English Lightning fast and portable programming language! What is Photon? Photon is a programming language aimed at filling th

William 58 Dec 27, 2022
ASGI support for the Tartiflette GraphQL engine

tartiflette-asgi is a wrapper that provides ASGI support for the Tartiflette Python GraphQL engine. It is ideal for serving a GraphQL API over HTTP, o

tartiflette 99 Dec 27, 2022
A real time webchat made in graphql

Graphql Chat. This is a real time webchat made in graphql. Description Welcome to my webchat api, here i put my knowledge in graphql to work. Requirem

Nathan André 1 Jan 03, 2022
An unofficial Blender add-on for Autodesk's Arnold render engine.

Arnold for Blender Arnold for Blender (or BtoA) provides a bridge to the Arnold renderer from within Blender's standard interface. BtoA is an unoffici

Luna Digital, Ltd. 89 Dec 28, 2022
Django registration and authentication with GraphQL.

Django GraphQL Auth Django registration and authentication with GraphQL. Demo About Abstract all the basic logic of handling user accounts out of your

pedrobern 301 Dec 09, 2022