sendgrid/sendgrid-python

Make SendGrid Endpoint URL a Global Constant for Easier Custom Implementation

FredericoIsaac opened this issue · 0 comments

Introduction

Hello,

I would like to suggest an enhancement to the SendGrid Python client. Currently, the endpoint URL for sending emails is embedded within the client implementation. To improve flexibility and make it easier for developers to send emails without using the SendGrid client, I propose the following changes:

  1. Define the endpoint URL as a global constant:

Create a separate configuration file (e.g., config.py) that contains the endpoint URL, such as "https://api.sendgrid.com/v3/mail/send". This way, the URL can be easily referenced and modified if needed.

  1. Construct the URL using base and version constants:

Instead of hardcoding the full endpoint URL, define the base URL and version separately, and construct the full URL dynamically. This allows for easier updates and maintenance.

Proposed Changes:

  • Create a config.py file with the following content:
# config.py
BASE_URL = "https://api.sendgrid.com"
API_VERSION = "v3"
SEND_EMAIL_ENDPOINT = f"{BASE_URL}/{API_VERSION}/mail/send"
  • Update the existing code to use the global constant:
from .config import SEND_EMAIL_ENDPOINT

class BaseInterface(object):
    def __init__(self, auth, impersonate_subuser):
        self.auth = auth
        self.impersonate_subuser = impersonate_subuser
        self.version = __version__
        self.useragent = 'sendgrid/{};python'.format(self.version)
        self.host = SEND_EMAIL_ENDPOINT
        
        self.client = python_http_client.Client(
            host=self.host,
            request_headers=self._default_headers,
            version=3
        )
  • Example for sending emails using requests:
import requests
from .config import SEND_EMAIL_ENDPOINT

def send_email(api_key, from_email, to_email, subject, content):
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "personalizations": [
            {
                "to": [{"email": to_email}],
                "subject": subject
            }
        ],
        "from": {"email": from_email},
        "content": [{"type": "text/plain", "value": content}]
    }
    response = requests.post(SEND_EMAIL_ENDPOINT, headers=headers, json=data)
    return response

# Example usage
api_key = "your_sendgrid_api_key"
response = send_email(api_key, "from@example.com", "to@example.com", "Subject", "Email content")
print(response.status_code, response.json())

These changes will provide more flexibility for developers and make the codebase easier to maintain.

Thank you for considering this enhancement.

Best regards,