Skip to content

Commit 510c0f7

Browse files
committed
formatting
1 parent 6f8bb99 commit 510c0f7

File tree

1 file changed

+74
-72
lines changed

1 file changed

+74
-72
lines changed

source/integrations/fastapi-integration.txt

Lines changed: 74 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -125,40 +125,44 @@ Define Your Database Models
125125
Our application has three models, the ``StudentModel``, the
126126
``UpdateStudentModel``, and the ``StudentCollection``.
127127

128-
StudentModel Class
129-
``````````````````
130128

131-
This is the primary model we use as the `response model
132-
<https://fastapi.tiangolo.com/tutorial/response-model/>`__ for the majority of
133-
our endpoints.
134129

135-
MongoDB uses ``_id`` as the default UUID on its documents. However, `pydantic
136-
<https://pydantic-docs.helpmanual.io/>`__, the data validation
137-
framework used by FastAPI, leading underscores indicate that a variable is private, meaning you
138-
cannot assign it a value. Therefore, we name the field ``id`` but give it an
139-
alias of ``_id`` and set ``populate_by_name`` to ``True`` in the model's
140-
``model_config``. We also set this ``id`` value automatically to ``None``, so
141-
that can create a new student with out specifying it.
130+
.. procedure::
131+
:style: connected
142132

143-
.. note:: BSON to JSON Mapping
133+
.. step:: StudentModel Class
144134

145-
FastAPI encodes and decodes data as JSON strings, which do not support all the
146-
data types that MongoDB's BSON data type can store. BSON has support for
147-
more non-JSON-native data types, including ``ObjectId`` which is used for
148-
the default UUID attribute, ``_id``. Because of this, you must convert
149-
``ObjectId`` objects to strings before storing them in the ``_id`` field.
135+
This is the primary model we use as the `response model
136+
<https://fastapi.tiangolo.com/tutorial/response-model/>`__ for the majority
137+
of our endpoints.
150138

151-
For more information about how BSON compares to JSON, see this `JSON and BSON
152-
<https://www.mongodb.com/json-and-bson>`__ MongoDB article.
139+
MongoDB uses ``_id`` as the default UUID on its documents. However,
140+
`pydantic <https://pydantic-docs.helpmanual.io/>`__, the data validation
141+
framework used by FastAPI, leading underscores indicate that a variable is
142+
private, meaning you cannot assign it a value. Therefore, we name the field
143+
``id`` but give it an alias of ``_id`` and set ``populate_by_name`` to
144+
``True`` in the model's ``model_config``. We also set this ``id`` value
145+
automatically to ``None``, so that can create a new student with out specifying it.
153146

154-
Define the ``StudentModel`` class using the following code:
147+
.. note:: BSON to JSON Mapping
155148

156-
.. code-block:: python
149+
FastAPI encodes and decodes data as JSON strings, which do not support
150+
all the data types that MongoDB's BSON data type can store. BSON has
151+
support for more non-JSON-native data types, including ``ObjectId`` which
152+
is used for the default UUID attribute, ``_id``. Because of this, you
153+
must convert ``ObjectId`` objects to strings before storing them in the
154+
``_id`` field.
155+
156+
For more information about how BSON compares to JSON, see this `JSON and
157+
BSON <https://www.mongodb.com/json-and-bson>`__ MongoDB article.
157158

158-
# Represents an ObjectId field in the database.
159-
# It will be represented as a `str` on the model so that it can be
160-
serialized to JSON.
161-
PyObjectId = Annotated[str, BeforeValidator(str)]
159+
Define the ``StudentModel`` class using the following code:
160+
161+
.. code-block:: python
162+
163+
# Represents an ObjectId field in the database.
164+
# It will be represented as a `str` on the model so that it can be serialized to JSON.
165+
PyObjectId = Annotated[str, BeforeValidator(str)]
162166

163167
class StudentModel(BaseModel):
164168
"""
@@ -186,60 +190,58 @@ Define the ``StudentModel`` class using the following code:
186190
},
187191
)
188192

189-
UpdateStudentModel Class
190-
````````````````````````
191-
192-
The ``UpdateStudentModel`` has two key differences from the ``StudentModel``:
193-
194-
- It does not have an ``id`` attribute, as this cannot be modified
195-
- All fields are optional, so you can supply only the fields you want to update
196-
197-
Define the ``UpdateStudentModel`` class using the following code:
193+
.. step:: UpdateStudentModel Class
198194

199-
.. code-block:: python
195+
The ``UpdateStudentModel`` has two key differences from the ``StudentModel``:
196+
197+
- It does not have an ``id`` attribute, as this cannot be modified
198+
- - All fields are optional, so you can supply only the fields you want to update
199+
200+
Define the ``UpdateStudentModel`` class using the following code:
201+
202+
.. code-block:: python
200203

201-
class UpdateStudentModel(BaseModel):
202-
"""
203-
A set of optional updates to be made to a document in the database.
204-
"""
205-
206-
name: Optional[str] = None
207-
email: Optional[EmailStr] = None
208-
course: Optional[str] = None
209-
gpa: Optional[float] = None
210-
model_config = ConfigDict(
211-
arbitrary_types_allowed=True,
212-
json_encoders={ObjectId: str},
213-
json_schema_extra={
214-
"example": {
204+
class UpdateStudentModel(BaseModel):
205+
"""
206+
A set of optional updates to be made to a document in the database.
207+
"""
208+
209+
name: Optional[str] = None
210+
email: Optional[EmailStr] = None
211+
course: Optional[str] = None
212+
gpa: Optional[float] = None
213+
model_config = ConfigDict(
214+
arbitrary_types_allowed=True,
215+
json_encoders={ObjectId: str},
216+
json_schema_extra={
217+
"example": {
215218
"name": "Jane Doe",
216219
"email": "[email protected]",
217-
"course": "Experiments, Science, and Fashion in Nanophotonics",
218220
"gpa": 3.0,
219-
}
220-
},
221-
)
221+
}
222+
},
223+
)
222224

223-
StudentCollection Class
224-
```````````````````````
225225

226-
The ``StudentCollection`` class is defined to encapsulate a list of
227-
``StudentModel`` instances. In theory, the endpoint could return a top-level
228-
list of ``StudentModel`` objects, but there are some vulnerabilities associated with
229-
returning JSON responses with top-level lists.
226+
.. step:: StudentCollection Class
230227

231-
Define the ``StudentCollection`` class using the following code:
228+
The ``StudentCollection`` class is defined to encapsulate a list of
229+
``StudentModel`` instances. In theory, the endpoint could return a top-level
230+
list of ``StudentModel`` objects, but there are some vulnerabilities
231+
associated with returning JSON responses with top-level lists.
232232

233-
.. code-block:: python
233+
Define the ``StudentCollection`` class using the following code:
234+
235+
.. code-block:: python
234236

235-
class StudentCollection(BaseModel):
236-
"""
237-
A container holding a list of `StudentModel` instances.
237+
class StudentCollection(BaseModel):
238+
"""
239+
A container holding a list of `StudentModel` instances.
238240

239-
This exists because providing a top-level array in a JSON response can be a `vulnerability <https://haacked.com/archive/2009/06/25/json-hijacking.aspx/>`__
240-
"""
241+
This exists because providing a top-level array in a JSON response can be a `vulnerability <https://haacked.com/archive/2009/06/25/json-hijacking.aspx/>`__
242+
"""
241243

242-
students: List[StudentModel]
244+
students: List[StudentModel]
243245

244246
Create Your Application Routes
245247
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -272,7 +274,7 @@ Our application has five routes, as shown in the `running application homepage <
272274
.. procedure::
273275
:style: connected
274276

275-
.. step:: Create Your Student Route
277+
.. step:: Student Routes
276278

277279
The ``create_student`` route receives the new student data as a JSON string
278280
in a ``POST`` request. We must decode this JSON request body into a Python
@@ -312,7 +314,7 @@ Our application has five routes, as shown in the `running application homepage <
312314
)
313315
return created_student
314316

315-
.. step:: Create Your Read Routes
317+
.. step:: Read Routes
316318

317319
The application has two read routes: one for viewing all students, and one
318320
for viewing an individual student specified by their ``id``.
@@ -370,7 +372,7 @@ Our application has five routes, as shown in the `running application homepage <
370372

371373
raise HTTPException(status_code=404, detail="Student {id} not found")
372374

373-
.. step:: Create Your Update Route
375+
.. step:: Update Route
374376

375377
The ``update_student`` route is like a combination of the ``create_student``
376378
and the ``show_student`` routes. It receives the ``id`` of the student to
@@ -424,7 +426,7 @@ Our application has five routes, as shown in the `running application homepage <
424426

425427
raise HTTPException(status_code=404, detail=f"Student {id} not found")
426428

427-
.. step:: Create Your Delete Route
429+
.. step:: Delete Route
428430

429431
.. code-block:: python
430432

0 commit comments

Comments
 (0)