Prerequisites
- Python 3.8 or later
- A FastAPI project with an ASGI server such as Uvicorn
- Authorize your sending domain
- Create or retrieve your SendLayer API key
Installation
Install the SDK along with FastAPI, Uvicorn, andpydantic-settings.
Storing your API key
Create a.env file in your project root.
.env
app/config.py
.env to .gitignore so the key stays out of version control.
Creating the email client
Wrap the client in a cached factory.lru_cache returns the same instance on every call, which makes it a clean FastAPI dependency.
app/email_client.py
Defining the request model
Pydantic validates the payload before your code runs.EmailStr rejects malformed addresses, and min_length blocks empty fields.
app/schemas.py
EmailStr requires the email-validator package. Install it with pip install "pydantic[email]" if it is not already present.Sending an email from an endpoint
Declare the endpoint withdef rather than async def. FastAPI then runs it in a thread pool, so the synchronous SDK call never blocks the event loop.
app/main.py
reply_to field points at the person who filled in the form, so support agents can reply from their inbox.
Use a
sender address on a domain you authorized in SendLayer. Requests from an unauthorized domain fail.Sending in the background
For endpoints where the caller does not need the message ID, hand the send toBackgroundTasks. FastAPI returns the response first and runs the task afterward.
app/routers/signup.py
app/main.py
Testing the endpoint
Start the server, then post a request from another terminal.http://localhost:8000/docs and send the request from the generated Swagger interface.
Open the Email Logs page in your SendLayer dashboard to confirm delivery.
Next Steps
Python SDK Reference
Review every method and parameter in the Python SDK.
Managing Webhooks
Create, list, and delete webhook subscriptions.
Retrieving Events
Query delivery events for any message.
Rate Limits
Understand recipient and request limits.
Frequently asked questions
Why is the parameter called sender instead of from?
Why is the parameter called sender instead of from?
from is a reserved keyword in Python, so it cannot be a keyword argument. The Python SDK uses sender for the sending address.Why does my endpoint return a 422 error?
Why does my endpoint return a 422 error?
Pydantic rejected the payload. The response body lists each failing field, so check that the request matches your request model.
How do I keep the API key out of the code?
How do I keep the API key out of the code?
Load it from the environment through a
Settings class. Uvicorn reads the process environment, so hosting platforms can inject the value at deploy time.