Setting up FastAPI:
FastAPI is a modern, fast (high-performance) web framework for building APIs with Python. In this code, we import the necessary modules from FastAPI, motor, and Ariadne libraries.
Establishing a MongoDB Connection:
We connect to a MongoDB database using AsyncIOMotorClient. This client allows us to perform asynchronous operations with MongoDB. We define a database named "graphql" and a collection named "test" to store user data.
Defining FastAPI Endpoints:
We define several HTTP endpoints to perform CRUD operations on user data. These include:
- POST /users: Creates a new user in the database.
- GET /users/{name}: Retrieves user data by name.
- PUT /users/{name}: Updates user data by name.
- DELETE /users/{name}: Deletes a user by name.
Error handling is implemented using HTTPException to return appropriate HTTP status codes and error messages.
Setting up GraphQL:
We define a GraphQL schema using gql, specifying a Query type with a "users" field. The "users" field allows querying user data, optionally filtered by name.
A resolver function, resolve_users, is implemented to fetch user data from MongoDB based on the provided query parameters.
We create an executable schema using make_executable_schema to integrate GraphQL with FastAPI.
Defining Pydantic Models:
Pydantic models, UserCreate and UserUpdate, are defined to represent the structure of user data for request payloads.
The User class inherits from UserCreate to maintain type consistency, ensuring that user data conforms to the expected structure.
For a more detailed exploration of the Grapql with fastapi setup, you can refer to the GitHub repository:
GitHub Repository.