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
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 new GraphQL library for Python 🍓

Strawberry GraphQL Python GraphQL library based on dataclasses Installation ( Quick Start ) The quick start method provides a server and CLI to get go

Strawberry GraphQL 2.8k Jan 01, 2023
Blazing fast GraphQL endpoints finder using subdomain enumeration, scripts analysis and bruteforce.

Graphinder Graphinder is a tool that extracts all GraphQL endpoints from a given domain. Run with docker docker run -it -v $(pwd):/usr/bin/graphinder

Escape 76 Dec 28, 2022
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

tartiflette 839 Dec 31, 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
Adds GraphQL support to your Flask application.

Flask-GraphQL Adds GraphQL support to your Flask application. Usage Just use the GraphQLView view from flask_graphql from flask import Flask from flas

GraphQL Python 1.3k Dec 31, 2022
ReplAPI.it A Simple and Complete Replit API Package

Notice: Currently this project is just a framework. It does not work yet. If you want to get updated when 1.0.0 is released, then click Watch - Custo

The ReplAPI.it Project 10 Jun 05, 2022
This is a graphql api build using ariadne python that serves a graphql-endpoint at port 3002 to perform language translation and identification using deep learning in python pytorch.

Language Translation and Identification this machine/deep learning api that will be served as a graphql-api using ariadne, to perform the following ta

crispengari 2 Dec 30, 2021
Authorization middleware for GraphQL

GraphQL-Authz is a Python3.6+ port of GraphQL-Authz, the node.js implementation for the Casbin authorization middleware.

2 Oct 24, 2022
A Python dependency resolver

python-resolver A Python dependency resolver. Issues Only supports wheels (no sdists!) Usage Python library import packaging.requirements import resol

Filipe Laíns 19 Jun 29, 2022
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

GraphQL 14k Jan 01, 2023
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
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

Isa 1 Nov 04, 2021
This is a minimal project using graphene with django and user authentication to expose a graphql endpoint.

Welcome This is a minimal project using graphene with django and user authentication to expose a graphql endpoint. Definitely checkout how I have mana

yosef salmalian 1 Nov 18, 2021
Django GraphQL User Management

Django GraphQL User Management An app that explores User management with GraphQL using Graphene in Django. Topics covered: Login. Log Out. Authenticat

0101 Solutions 4 Feb 22, 2022
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
GraphiQL & the GraphQL LSP Reference Ecosystem for building browser & IDE tools.

Black Lives Matter 🖤 GraphQL IDE Monorepo Security Notice: All versions of graphiql 1.4.7 are vulnerable to an XSS attack in cases where the GraphQ

GraphQL 14.5k Jan 08, 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
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