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!
pode ter graphQL e REST na mesma aplicação?
Edu cada vez me conquista mais! O cara é feito de sonho, luz e chocolate… só pode!
Pacote básico: aquele like e aquele obrigado.
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
você tem um curso de python ensinando do zero ao avançado ?
Please try to make videos in English . I was learning FastApi GraphQL with Strawberry. It could have helped me a lot.
No caso, REST torna a aplicação menos performatica
Excellent job of yours!!!
Obrigado, tudo foi muito compreensível. Eu tenho uma pergunta, é possível mudar o sqlmodel para tortoise orm?
Parabéns pelo conteúdo, vc explica MT bem. Queria saber se vc tem algum curso estruturado de python ou algo assim ?
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.
Muito massaaa vei não sabia que isso era assim
Fica fácil prender assim kkkk. Parabéns 🙏
Show!!!!!!
Alguma indicação de curso de FastApi?
Ainda bem que você deixa as aulas salvas. Muito top essas aulas.