import os, sendgrid
from fastapi import FastAPI, BackgroundTasks
from sendgrid.helpers.mail import Mail
app = FastAPI()
sg = sendgrid.SendGridAPIClient(api_key value os.environ.get('SENDGRID_API_KEY'))
def send_welcome(to_email: str):
message = Mail(
from_email='[YOUR_VERIFIED_SENDER]', # verified sender
to_emails=to_email,
subject='Welcome',
plain_text_content='Welcome aboard')
response = sg.send(message)
if response.status_code != 202:
print('sendgrid failed', response.status_code, response.body)
@app.post('/signup')
def signup(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_welcome, 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.