Python Live #185 featuring GraphQL with Strawberry and FastAPI

Posted by


GraphQL is a query language for APIs that allows clients to request exactly the data they need, making it more flexible than traditional REST APIs. In this tutorial, we will explore how to create a GraphQL API using Strawberry and FastAPI, two popular Python frameworks.

Strawberry is a new GraphQL library for Python that is designed to be easy to use and intuitive. FastAPI is a modern web framework for building APIs with Python that is known for its high performance and ease of use.

Before we dive into the tutorial, make sure you have Python installed on your machine. You can install it by downloading it from the official website or using a package manager like Homebrew on macOS or Chocolatey on Windows.

Once you have Python installed, you can create a new virtual environment for our project by running the following command:

python3 -m venv venv

Next, activate the virtual environment by running the following command:

source venv/bin/activate

Now that we have our virtual environment set up, let’s install the necessary packages for our project:

pip install fastapi uvicorn strawberry-graphql

Now that we have everything installed, let’s create a new file called main.py and add the following code:

from fastapi import FastAPI
from strawberry.asgi import GraphQL

import strawberry

app = FastAPI()

@strawberry.type
class Query:
    hello: str = "Hello, World!"

schema = strawberry.Schema(query=Query)

@app.get("/")
def index():
    return {"message": "Welcome to the GraphQL API"}

app.add_route("/graphql", GraphQL(schema))

In this code, we are creating a simple FastAPI application with a single route that returns a welcome message. We are also defining a GraphQL schema with a single query field called hello that returns a string.

To run the application, simply execute the following command:

uvicorn main:app --reload

This will start the FastAPI server, and you should see a message indicating that the server is running. You can now navigate to http://localhost:8000 in your browser to see the welcome message.

To test the GraphQL API, you can use tools like GraphiQL or GraphQL Playground. Simply navigate to http://localhost:8000/graphql in your browser to access the GraphQL Playground.

In the Playground, you can enter queries to interact with the GraphQL API. For example, you can run the following query to retrieve the value of the hello field:

query {
  hello
}

This should return the response {"data":{"hello":"Hello, World!"}}, indicating that the query was successful.

This is just a simple example of how to create a GraphQL API using Strawberry and FastAPI. You can expand on this example by adding more query fields, mutations, and types to create a more complex API.

I hope this tutorial has been helpful in getting you started with GraphQL and Strawberry. If you have any questions or run into any issues, feel free to reach out for help. Happy coding!

0 0 votes
Article Rating

Leave a Reply

16 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@zec_s
10 days ago

pode ter graphQL e REST na mesma aplicação?

@AnSoNeves
10 days ago

Edu cada vez me conquista mais! O cara é feito de sonho, luz e chocolate… só pode!

@snowman_brazil
10 days ago

Pacote básico: aquele like e aquele obrigado.

@KivySchool
10 days ago

kkkkkk tudo que eu estou aprendendo eu acho um tutorial seu
você se tornou meu canal número 1 agora <3
ótimo trabalho, irmão

@guilhermehenrique5900
10 days ago

você tem um curso de python ensinando do zero ao avançado ?

@SirJagerYT
10 days ago

Please try to make videos in English . I was learning FastApi GraphQL with Strawberry. It could have helped me a lot.

@omnidev1370
10 days ago

No caso, REST torna a aplicação menos performatica

@etbrful
10 days ago

Excellent job of yours!!!

@darkaxce
10 days ago

Obrigado, tudo foi muito compreensível. Eu tenho uma pergunta, é possível mudar o sqlmodel para tortoise orm?

@jpsamarino3
10 days ago

Parabéns pelo conteúdo, vc explica MT bem. Queria saber se vc tem algum curso estruturado de python ou algo assim ?

@r2rick
10 days ago

Eduardo Mendes, poderia fazer uma aula mais avançada de GraphQL? Por exemplo, como trabalhar funções de Agregação e Agrupamento como no SQL (count, min, max, stddev, mean) e Groupby com Having ? Ainda, GraphQL é interessante para trabalhar com séries temporais? Obrigado.

@VulgoLG
10 days ago

Muito massaaa vei não sabia que isso era assim

@LieviSilva
10 days ago

Fica fácil prender assim kkkk. Parabéns 🙏

@ricardojob
10 days ago

Show!!!!!!

@carlosdornelesdev
10 days ago

Alguma indicação de curso de FastApi?

@antunesce
10 days ago

Ainda bem que você deixa as aulas salvas. Muito top essas aulas.

16
0
Would love your thoughts, please comment.x
()
x