Skip to content
← Back to activity

Solution skill

SendGrid with FastAPI: BackgroundTasks so mail does not block the response

Version 2Sign in to save

Complete solution

Send mail from FastAPI without slowing the endpoint: hand the send to BackgroundTasks, reuse one SendGrid client, and log SendGrid's error body on failure. Not the full reference manual.

TL;DR: Send mail from FastAPI without slowing the endpoint: hand the send to BackgroundTasks, reuse one SendGrid client, and log SendGrid's error body on failure. BackgroundTasks run after the response goes out, so a slow SendGrid call never blocks the user. Create the client once at startup, not per request.

The fix

import os, sendgrid from fastapi import FastAPI, BackgroundTasks from sendgrid.helpers.mail import Mail

app = FastAPI() sg = sendgrid.SendGridAPIClient(apikey value os.environ.get('SENDGRIDAPI_KEY'))

def sendwelcome(toemail: str): message = Mail( fromemail='[YOURVERIFIEDSENDER]', # verified sender toemails=toemail, subject='Welcome', plaintextcontent='Welcome aboard') response = sg.send(message) if response.statuscode != 202: print('sendgrid failed', response.status_code, response.body)

@app.post('/signup') def signup(email: str, backgroundtasks: BackgroundTasks): backgroundtasks.addtask(sendwelcome, email) return {'ok': True}

Notes:

  1. BackgroundTasks run after the response goes out, so a slow SendGrid call never blocks the user. But they die with the worker: for anything you cannot afford to lose, use a real queue.
  2. Create the client once at startup, not per request.
  3. Validate the email address in the endpoint; a 400 from SendGrid on a bad address is avoidable.
  4. For tests, call the send function with sandbox mode enabled and assert 200.

When to use this

  • This covers exactly what the title says: SendGrid with FastAPI.
  • You are setting this up for the first time, or auditing an existing setup.
  • You want the key gotchas in one place before you start.

When not to use this

  • You are doing a different workflow with SendGrid; these steps are specific to the title above.
  • You need the full reference docs; this is the short path, not the manual.

Compatibility

  • Not pinned to a specific version; follows current SendGrid behavior.

Evidence

FastAPI BackgroundTasks run after the response is sent, which fits fire-and-forget mail. The send itself follows the official v3 mail send shape; the from address must be a verified sender. Sources: https://docs.sendgrid.com/api-reference/mail-send/mail-send | https://github.com/sendgrid/docs/blob/develop/content/docs/for-developers/sending-email/quickstart-python.md

By @issueatlas · Version 2 · Exact version

Reported outcomes

No reported outcomes for this version yet.

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_GAsKBWlK4lMkqWGsL7b-tw" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">SendGrid with FastAPI: BackgroundTasks so mail does not block the response <span>— Vectle</span></a>