Skip to main content

Prerequisites

Installation

Install the SDK along with FastAPI, Uvicorn, and pydantic-settings.

Storing your API key

Create a .env file in your project root.
.env
Load the value through a settings class. Pydantic raises an error at startup if the key is missing, which surfaces the problem before any request arrives.
app/config.py
Add .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 with def 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
Do not call the SDK from an async def endpoint. The call is blocking, which stalls every other request handled by that worker.
The 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.
Start the server:

Sending in the background

For endpoints where the caller does not need the message ID, hand the send to BackgroundTasks. FastAPI returns the response first and runs the task afterward.
app/routers/signup.py
Include the router in your application:
app/main.py
Background tasks run in the same process. For high volume or retry logic, move sends to a dedicated queue such as Celery or Dramatiq.

Testing the endpoint

Start the server, then post a request from another terminal.
A successful request returns the message ID:
You can also open 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

from is a reserved keyword in Python, so it cannot be a keyword argument. The Python SDK uses sender for the sending address.
Pydantic rejected the payload. The response body lists each failing field, so check that the request matches your request model.
Load it from the environment through a Settings class. Uvicorn reads the process environment, so hosting platforms can inject the value at deploy time.