DEV Community

loading...
Cover image for GraphQL and FastAPI Combination

GraphQL and FastAPI Combination

Bek Brace
Hey everyone πŸ‘‹, this is Bek Brace. I teach programming on YouTube. Love coffee, ramen and Atlanta Hawks!I speak 5 Human languages and several Computer languages.
・3 min read

GraphQL is an abbreviation for Graph Query Language.
So it's a Query Language for reading data from API.
Unlike most query languages (such as SQL), you don’t use GraphQL to query a particular type of data store (such as a PostgreSQL database for example).
Instead, you use GraphQL to query data from any number of different sources.

So, to make things clearer , in traditional REST API, you consume apis using REST and we have done that so many times with Flask, Django and FastAPI by sending different HTTP request methods like GET, POST, PUT , and DELETE to the API using path or URLS

Now the problem with HTTP requests is that when the request is received from the front-end user,
the API responds with everything it has, a full payload that contains data that might not be useful to you as a developer

The other problem is the opposite, which means that you might want to fetch multiple data or get multiple resources simultaneously, and this is not possible, because there is no enough data per HTTP request.

And there comes the power of GraphQL
GRAPHQL solved this problem by improving upon the idea of receiving a bulk of unnecessary data or fetching less than expected, so instead of these request URLS or many endpoints for HTTP methods; graphql has a single entry point; ( slid 2 of code) so you can query data now very easily by specifying what type of data exactly you're looking for, and the response you'll get will exactly match your query, in JSON format of course.

The way this works is by start defining a schema with objects using type keyword, and a type can have multiple fields like an id, and if you want to make it non-nullable then add the exclamation mark after [ Analogist to NOT NULL in SQL ], you can also add integers, strings and boolean values.

type Author {
    id:ID!
    age: 56
    genre: "horror"
    american: True
    books: [Books]
    symbol: ✍️
} 
Enter fullscreen mode Exit fullscreen mode

You can also create relationship with another type, so an author can have many books , which we can represent by wrapping the type in bracket , and on the other side, the books belong to an author

type Books{
    language: String!
    number: int
    author: Author
        symbol: πŸ“š
}
Enter fullscreen mode Exit fullscreen mode

GraphQL and FastAPI

Now, we are going to use GraphQL to fetch data from FASTAPI, and we could use something like Strawbery or Ariadne, but Starlette, and when I say Starlette, I implicitly mean FastAPI, so Starlette includes optional support for GraphQL, using the graphene library.

Install fastAPI : pip install fastapi
Install Graphene : pip install "graphene>=2.0"

https://graphene-python.org
Graphene is a library for building GraphQL APIs in Python easily, so it's a Server library, and its main goal is to provide a simple but extendable API for making developers' lives easier.

import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp

class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value=", world 🌎 !"))

    def resolve_hello(self, info, name):
        return "Hello " + name

app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))
Enter fullscreen mode Exit fullscreen mode

Here we are using .add_route, that is the way to add a route in Starlette (inherited by FastAPI) without declaring the specific operation (as would be with .get(), .post(), etc).

Run the file : uvicorn main:app --reload
Now we will load up the page in the browser, we will be served the GraphiQL tool, which you can use to interact with GraphQL API

GitHub logo BekBrace / GraphQL-FastAPI-Code

This is an introduction to GraphQL, and how to combine FastAPI code with GraphQL to run queries and receive data in GraphiQL Tool

Discussion (0)