---
title: "💭 Background Tasks - FastAPI"
description: "!https://fastapi.tiangolo.com/tutorial/background-tasks/"
date: 2024-07-03
published: true
tags:
  - fastapi
  - webdev
  - thought
template: link
---


<div class="embed-card embed-card-external">
  <a href="https://fastapi.tiangolo.com/tutorial/background-tasks/" class="embed-card-link" target="_blank" rel="noopener noreferrer">
    <div class="embed-card-image">
      <img src="https://fastapi.tiangolo.com/assets/images/social/tutorial/background-tasks.png" alt="Background Tasks - FastAPI — FastAPI framework, high performance, easy to learn, fast to code, ready for production" loading="lazy">
    </div>
    <div class="embed-card-content">
      <div class="embed-card-title">Background Tasks - FastAPI</div>
      <div class="embed-card-description">FastAPI framework, high performance, easy to learn, fast to code, ready for production</div>
      <div class="embed-card-meta">fastapi.tiangolo.com</div>
    </div>
  </a>
</div>


fastapi comes with a concept of background tasks which are functions that can be ran in the background after a function has been ran.  This is handy for longer running functions that may take some time and you want to have fast response times.

Here is an example from the docs

``` python
from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)


@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}
```

!!! note

    This post is a <a href="/thoughts/" class="wikilink" data-title="Thoughts" data-description="These are generally my thoughts on a web page or some sort of url, except a rare few don&#39;t have a link. These are dual published off of my..." data-date="2024-04-01">thought</a>. It's a short note that I make
    about someone else's content online <a href="/tags/thoughts/" class="hashtag-tag" data-tag="thoughts" data-count=2 data-reading-time=3 data-reading-time-text="3 minutes">#thoughts</a>
