Codementor Events

Building APIs with GraphQL and Flask

Published Apr 07, 2023

Building APIs with GraphQL and Flask

  • Introduction
     

    1. GraphQL is a query language for APIs and a server-side runtime that allows clients to request only the data that they need from APIs.
    2. GraphQL is meant to be a more efficient and flexible alternative to REST.
  • Initial steps   

    1. Create virtual environment 
    2. Install requirements 
-  Flask 
- Flask-sqlalchemy 
- Flask\_login 
- Flask\_migration 
- Psycopg2-binary
  1. We are going to use the ariadne library to integrate graphql in flask for that install ariadne library using this command.
      pip install ariadne
  2. Configure flask app 
  3. Create models for your project and migrate 
  4. Create schema.graphql file which contain types of models field in your root directory
  • The Query and Mutation type 

Schema

    1. Every graphql service has a query and mutation type. These types are the same as regular types, but they are special because they define the entry point of every graphql query.
    2. Put this code in schema.graphql
  • Types and fields 

    1. The most basic components of a GraphQL schema are object types, which just represent a kind of object you can fetch from your service, and what fields it has. In the GraphQL schema language, for example
    2. Example

Type order all 

    • OrderAll    is a graphql object type, meaning it’s a type with some fields.
    • success, errors and order  are fields on the OrderAll type. That means success, errors and order are the only fields that can appear in graphql query that operates on the OrderAll type.
    • String is one of the built-in scalar types;  these are types that resolve to a single scalar object, and can’t have sub-selection in query.
    • String! means that the field is non-nullable, meaning that the Graphql service always gives you value when you query this field. We’ll represent those with an exclamation mark.
    • [Order]! Represent an array of Order objects. you can get every item of the array when you query the order field. it can have sub-selections in the query. 
  • Create function for graphql execution

    1. Create resource.py  file your app for implement graphql resolver(functions)
    2. Configure QueryType and MutationType from ariadne library  in project __init__ file

From ecommerce App

    • Import query and mutation in resource.py file it is used as wrapper in function which is map function to graphql query.
    • Create graphql query for get_all_user 
    • First create model for user 

Class User Model

    • Create user model in model.py file 
    • Add fields like username, email, mobile_number, password
    • Create to_dict function for return all data in dictionary it is helping for fetch particular data
  • Create get all user resolver
    1. Create function which return all users data in json

Def users

    1. “*_” in users function is use for ignore unwanted list of parameter
    2. In user_data we get list of all user data in json from database
    3. This function returns success and users,  where success contains Boolean value and users contain a list of user data. 
  • Now add decorator on users function
    1. @query.field(“users”)
    2. Where query is imported from the project init file.
    3. This decorator use for add map query function data to Query
  • Now your function looks like this.

query field users

  • Create type for user in schema.graphql file

type User                                  Type user result

    1. In User type we define all fields which is use in query
    2. In UserResult we define three fields which are used for retrieving data, if the query executes successfully we get True in  success and if we get any error then it shows in the errors field, users field is used to get any particular user field like mobile_number, email, etc.
    3. Now add the UserResult type in the Query type.

Type Query

  • Example of graphql query for get_all_user

Query

    1. This is query type graphql query for all user
    2. The first user’s name contains a schema in Query type.
    3. The second users contains object of User in UserResult type [User] 
  • Add some configuration and url for graphql

From aride consultants

    1. Import load_schema_from_path for load schema.graphql file in app.py file
    2. Give schema.graphql file path in load_schema_from_path, stored in type_defs variable
    3. For making graphql schema executable import make_executable_schema from ariadne
    4. Give type_defs and [query, mutation] in make_executable_schema’s parameter.

def graphql ui

    1. Create route for graphql query terminal
    2. For graphql ui import PLAYGROUND_HTML from ariadne.constants, it provide html code for graphql terminal page
    3. Run localhost:5000/graphql,  your page looks like the page below.

prettify History

  •   Create another route for POST method with same endpoint

graphql server

    1. Post method is used for sending graphql query to server and getting response.
    2. graphql_server function returns json data and status_code.
    3. Passing a graphql query in the left display you will get the output on the right display. 

Example for Mutation Mutation is used to make any update, delete operation with graphql. Creating mutation for update user with graphql First create graphql schema in Mutation type

  • Example for Mutation
    1. Mutation is used to make any update, delete operation with graphql.
    2. Creating mutation for update user with graphql
    3. First create graphql schema in Mutation type 

type mutation

    1. We create update_user schema
    2. update_user is the name of the schema and it contains id, username, email, mobile_number, etc. fields.
    3. In the end User is used to get updated values of fields.
  • Now we create a resolver function for update_user. 

mutation field update user

    1. Creating update_user function in schema.py.
    2. Add mutation decorator in update_user function
    3. @mutation.field(“update_user”)
    4. update_user takes id, username, email, mobile_number etc. in parameter
    5. And this function returns a User object.
  • Create graphql query for execute

Update user username

  • This is a mutation type query for update_user name and it contains some parameters and also we can get all user details after updating the user.
  • Conclusion Building APIs with GraphQL and Flask is a powerful combination that can greatly simplify API development. By using GraphQL as a query language and Flask as a web framework, developers can build flexible, scalable APIs that are easy to maintain and evolve over time. Through this documentation, you will learn how to integrate GraphQL with Flask and leverage the strengths of both technologies to build robust APIs that meet your specific requirements. By following the best practices and guidelines outlined in this documentation, you can ensure that your APIs are efficient, secure, and provide a great user experience.
Discover and read more posts from Margaret Dyreng
get started