First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.
And as the write operation doesn't use `async` and `await`, we define the function with normal `def`:
-```Python hl_lines="6-9"
-{!../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
## Add the background task
Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:
-```Python hl_lines="14"
-{!../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
`.add_task()` receives as arguments:
**FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards:
-//// tab | Python 3.10+
-```Python hl_lines="13 15 22 25"
-{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!}
-```
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
-////
-
-//// tab | Python 3.9+
-
-```Python hl_lines="13 15 22 25"
-{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!}
-```
-
-////
-
-//// tab | Python 3.8+
-
-```Python hl_lines="14 16 23 26"
-{!> ../../docs_src/background_tasks/tutorial002_an.py!}
-```
-
-////
-
-//// tab | Python 3.10+ non-Annotated
-
-/// tip
-
-Prefer to use the `Annotated` version if possible.
-
-///
-
-```Python hl_lines="11 13 20 23"
-{!> ../../docs_src/background_tasks/tutorial002_py310.py!}
-```
-
-////
-
-//// tab | Python 3.8+ non-Annotated
-
-/// tip
-
-Prefer to use the `Annotated` version if possible.
-
-///
-
-```Python hl_lines="13 15 22 25"
-{!> ../../docs_src/background_tasks/tutorial002.py!}
-```
-
-////
In this example, the messages will be written to the `log.txt` file *after* the response is sent.