GraphQL and FastAPI Combination
Tags: graphql, python, programming, database
Published: 2021-08-01 20:08:07

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

{% youtube 2_puWfTK8bQ %}


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: ✍️
} 
```
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: 📚
}
```

# 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)))
```

*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 BekBrace/GraphQL-FastAPI-Code no-readme %}