Home >Backend Development >Python Tutorial >Building a Contact Form Backend with FastAPI and Discord Integration

Building a Contact Form Backend with FastAPI and Discord Integration

Susan Sarandon
Susan SarandonOriginal
2025-01-07 20:24:401022browse

Building a Contact Form Backend with FastAPI and Discord Integration

This tutorial demonstrates building a robust and secure backend API using FastAPI to manage contact form submissions and relay them to a Discord channel via webhooks. We'll also address crucial CORS configuration for controlled access.

Prerequisites:

  • Python 3.11
  • FastAPI
  • httpx (for asynchronous HTTP requests)
  • A Discord webhook URL

Step 1: Project Setup

Create a project directory and install necessary packages:

<code class="language-bash">pip install fastapi uvicorn httpx python-dotenv</code>

Step 2: FastAPI Application Creation

Create main.py:

<code class="language-python">import os
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import httpx

app = FastAPI()

# CORS Configuration (Security!)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://vicentereyes.org", "https://www.vicentereyes.org"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)</code>

Step 3: Data Model Definition

Use Pydantic for data structure:

<code class="language-python">class FormData(BaseModel):
    name: str
    email: str
    message: str
    service: str
    companyName: str
    companyUrl: str</code>

Step 4: Submission Endpoint

Add the form submission handler:

<code class="language-python">@app.post("/submit/")
@app.post("/submit")  # Handles both /submit and /submit/
async def submit_form(form_data: FormData):
    try:
        # Format message for Discord
        message_content = {
            "content": f"New form submission:\n"
                       f"**Name:** {form_data.name}\n"
                       f"**Email:** {form_data.email}\n"
                       f"**Message:** {form_data.message}\n"
                       f"**Service:** {form_data.service}\n"
                       f"**Company Name:** {form_data.companyName}\n"
                       f"**Company URL:** {form_data.companyUrl}"
        }

        # Send to Discord webhook using httpx
        async with httpx.AsyncClient() as client:
            response = await client.post(os.environ["FASTAPI_DISCORD_WEBHOOK_URL"], json=message_content)

        if response.status_code != 204:
            raise HTTPException(status_code=response.status_code, detail="Discord message failed")

        return {"message": "Form data sent successfully"}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))</code>

Step 5: Environment Variables

Create a .env file:

<code>FASTAPI_DISCORD_WEBHOOK_URL=your_discord_webhook_url_here</code>

How It Works:

  1. Secure CORS: Limits access to your API to only authorized domains.
  2. Data Validation: Pydantic ensures data integrity.
  3. Asynchronous Discord Integration: Efficiently sends messages to Discord.
  4. Robust Error Handling: Provides informative error responses.

Running the Application:

<code class="language-bash">uvicorn main:app --reload</code>

Access the API at http://localhost:8000.

Security Best Practices:

  • Restrict CORS: Only allow necessary domains.
  • Environment Variables: Securely store sensitive information.
  • Input Validation: Always validate user input.
  • Comprehensive Error Handling: Avoid exposing sensitive details.

Frontend Integration Example:

<code class="language-javascript">fetch('your_api_url/submit', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ /* form data */ })
});</code>

Conclusion:

This secure FastAPI backend provides a reliable and efficient method for handling contact forms and integrating with Discord. The use of asynchronous operations and robust error handling ensures a high-performance and secure solution.

Code: https://www.php.cn/link/d92d7ec47187a662aacda2d4b4c7628e Live: https://www.php.cn/link/775bc655c77d679c193f1982dac04668

The above is the detailed content of Building a Contact Form Backend with FastAPI and Discord Integration. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn