没有合适的资源?快使用搜索试试~ 我知道了~
Developing an API with FastAPI and GraphQL
需积分: 0 0 下载量 64 浏览量
2023-03-17
17:02:47
上传
评论
收藏 331KB PDF 举报
温馨提示
试读
25页
Objectives By the end of this tutorial, you will be able to: Explain why you may want to use GraphQL over REST Use the Masonite ORM to interact with a Postgres database Describe what Schemas, Mutations, and Queries are in GraphQL Integrate GraphQL into a FastAPI app with Graphene Test a GraphQL API with Graphene and pytest Why GraphQL? (And why GraphQL over traditional REST?) REST is the de-facto standard for building web APIs. With REST, you have multiple endpoints for each CRUD operation: GE
资源推荐
资源详情
资源评论
Developing an API with FastAPI and
GraphQL
In this tutorial, you'll learn how to build a CRUD app with FastAPI, GraphQL, and the Masonite
ORM.
Objectives
By the end of this tutorial, you will be able to:
1. Explain why you may want to use GraphQL over REST
2. Use the Masonite ORM to interact with a Postgres database
3. Describe what Schemas, Mutations, and Queries are in GraphQL
4. Integrate GraphQL into a FastAPI app with Graphene
5. Test a GraphQL API with Graphene and pytest
Why GraphQL?
(And why GraphQL over traditional REST?)
REST is the de-facto standard for building web APIs. With REST, you have multiple endpoints for
each CRUD operation: GET, POST, PUT, DELETE. Data is gathered by accessing a number of
endpoints.
For example, if you wanted to get a particular user's profile info along with their posts and
relevant comments, you would need to call four different endpoints:
1. /users/ returns the initial user data
2. /users//posts returns all posts for a given user
3. /users//comments returns a list of comments per post
4. /users//comments returns a list of comments per user
This can result in request overfetching since you'll probably have to get much more data than you
need.
Moreover, since one client may have much different needs than other clients, request
overfetching and underfetching are common with REST.
GraphQL, meanwhile, is a query language for retrieving data from an API. Instead of having
multiple endpoints, GraphQL is structured around a single endpoint whose return value is
dependent on what the client wants instead of what the endpoint returns.
In GraphQL, you would structure a query like so to obtain a user's profile, posts, and comments:
query {
User(userId: 2){
name
posts {
title
comments {
body
}
1
2
3
4
5
6
7
8
Voila! You get all the data in just one request with no overfetching since we specified exactly what
we want.
FastAPI supports GraphQL via Starlette and Graphene. Starlette executes GraphQL queries
in a separate thread by default when you don't use async request handlers!
Why Masonite ORM?
The Masonite ORM is a clean, easy-to-use, object relational mapping library built for the Masonite
web framework. It builds on the Orator ORM, an Active Record ORM.
Masonite ORM was developed to be a replacement to Orator ORM as Orator no longer receives
updates and bug fixes.
It resembles other popular Active Record implementations, like Django's ORM, Laravel's Eloquent,
AdonisJS' Lucid, and Active Record in Ruby On Rails. With support for MySQL, Postgres, and
SQLite, it emphasizes convention over configuration, which makes it easy to create models since
you don't have to explicitly define every single aspect. Relationships are a breeze and very easy to
handle as well.
Although it's designed to be used in a Masonite web project, you can use the Masonite ORM with
other Python web frameworks or projects.
For more on the Masonite ORM and how to use it with FastAPI, check out Integrating the
Masonite ORM with FastAPI.
Project Setup
Create a directory to hold your project called "fastapi-graphql":
Create a virtual environment and activate it:
Feel free to swap out virtualenv and Pip for Poetry or Pipenv. For more, review Modern
Python Environments.
Create the following files in the "fastapi-graphql" directory:
}
comments {
body
}
}
}
9
10
11
12
13
14
$ mkdir fastapi-graphql
$ cd fastapi-graphql
1
2
$ python3.11 -m venv env
$ source env/bin/activate
(env)$
1
2
3
4
main.py
requirements.txt
1
2
Add the following requirements to requirements.txt file:
Uvicorn is an ASGI (Asynchronous Server Gateway Interface) compatible server that will be used
for standing up FastAPI.
Install the dependencies:
In the main.py file, add the following lines to kick-start the server:
To start the server, open your terminal, navigate to the project directory, and enter the following
command:
Navigate to http://localhost:8000 in your browser of choice. You should see the response:
You've successfully started up a simple FastAPI server. To see the beautiful docs FastAPI has for
us, navigate to http://localhost:8000/docs:
And http://localhost:8000/redoc:
fastapi==0.92.0
uvicorn==0.20.0
1
2
(env)$ pip install -r requirements.txt1
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def ping():
return {"ping": "pong"}
1
2
3
4
5
6
7
8
(env)$ uvicorn main:app --reload1
{
"ping": "pong"
}
1
2
3
Masonite ORM
Add the following requirements to the requirements.txt file:
Install the new dependencies:
Create the following folders:
The "models" folder will contain our model files, the "databases/migrations" folder will contain
our migration files, and the "config" folder will hold our Masonite Database configuration file.
Database Config
Inside the "config" folder, create a database.py file. This file is required for the Masonite ORM as
this is where we declare our database configurations.
For more info, visit the docs.
Within the database.py file, we need to add the DATABASE variable plus some connection
information, import the ConnectionResolver from masonite-orm.connections , and register
the connection details:
masonite-orm==2.18.6
psycopg2-binary==2.9.5
1
2
(env)$ pip install -r requirements.txt1
models
databases/migrations
config
1
2
3
# config/database.py
from masoniteorm.connections import ConnectionResolver
DATABASES = {
"default": "postgres",
"mysql": {
"host": "127.0.0.1",
"driver": "mysql",
"database": "masonite",
"user": "root",
1
2
3
4
5
6
7
8
9
10
11
Here, we defined three different database settings:
1. MySQL
2. Postgres
3. SQLite
We set the default connection to Postgres.
Note: Make sure you have a Postgres database up and running. Feel free to change the
default database connection.
Masonite Models
To create a new boilerplate Masonite model, run the following masonite-orm command from the
project root folder in your terminal:
You should see a success message:
So, this command should have created a User.py file in the "models" directory with the following
content:
"password": "",
"port": 3306,
"log_queries": False,
"options": {
#
}
},
"postgres": {
"host": "127.0.0.1",
"driver": "postgres",
"database": "test",
"user": "test",
"password": "test",
"port": 5432,
"log_queries": False,
"options": {
#
}
},
"sqlite": {
"driver": "sqlite",
"database": "db.sqlite3",
}
}
DB = ConnectionResolver().set_connection_details(DATABASES)
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
(env)$ masonite-orm model User --directory models1
Model created: models/User.py1
剩余24页未读,继续阅读
资源评论
魔都吴所谓
- 粉丝: 1w+
- 资源: 105
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功