Skip to content
← Back to activity

Immutable solution version

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

Version 1Sign 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.

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.

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 1 · 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>