This project illustrates how one would go about implementing a GraphQL Web API in Python using FastAPI and Strawberry.
This project was created by copying the swift-api-rest project and refactoring from REST to GraphQL.
Currently for simplicity the database is just one table. However in a real world application there should probably be a separate table for Author and a BookAuthor table that links Books and Authors. See Additional Considerations in swift-api-rest
for details.
source configure.sh
./watch.sh
Open the GraphiQL Explorer UI:
open http://127.0.0.1:8001/graphql
Paste this GraphQL code and click the play
button:
mutation {
createBook(book: {
title: "Test Book",
author: "Test Author",
datePublished: "2023-01-01",
coverImage: "http://example.com/cover.jpg"
}) {
id
title
author
datePublished
coverImage
}
}
Paste this GraphQL code and click the play
button:
query {
books {
id
title
author
datePublished
coverImage
}
}
source configure.sh
Open the project directory in Visual Studio Code:
code .
Format it with the black formatter:
black .
Correct the import order with isort:
isort .
Verify the typing:
mypy src/
Run the tests (from the command line):
pytest
Generate test coverage report:
coverage run -m pytest && coverage combine && coverage report
Run tests in multiple python environments (will run for 3.12, 3.11, 3.10):
hatch run test
Follow Set up Amplify CLI to install the AWS Amplify CLI.
Initialize the Amplify project:
amplify init
Enable container-based deployments (advanced option):
amplify configure project
Add API backend:
amplify add api
Copy app code (replace swiftapigraphql
with the resource name that Amplify generates for you):
amplify_dir=./amplify/backend/api/swiftapigraphql/src
# App
cp -pr src $amplify_dir/
cp -p requirements.txt $amplify_dir/
# Docker
cp -p docker/Dockerfile $amplify_dir/
cp -p docker/docker-compose.yml $amplify_dir/
Deploy service:
amplify push
NOTE:
-
amplify push
will build all your local backend resources and provision it in the cloud. -
amplify publish
will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud.
In order to do this you will need Podman. See Setup Podman on macOS for details.
Rebuild container image and start container:
inv podman
Delete container and image:
inv podman-delete
List tasks:
inv --list
swift-api-graphql
is distributed under the terms of the Apache 2.0 license.