Sending SMS & OTP Verification using Twilio in FastAPI with Python: Tutorial #31 📱🔐

Posted by


In this tutorial, we will be building a FastAPI web application that will allow users to send SMS messages for OTP verification using Twilio’s API. This will be a step-by-step guide that will walk you through the process of setting up your FastAPI project, integrating Twilio for sending SMS messages, and implementing OTP verification functionality.

Step 1: Setting up your FastAPI project
To get started, make sure you have Python installed on your system. You can install FastAPI using pip by running the following command:

pip install fastapi

Next, install the Uvicorn ASGI server that will be used to run the FastAPI application:

pip install uvicorn

Create a new directory for your FastAPI project and navigate to it in your terminal. Inside the project directory, create a new Python file called main.py.

Step 2: Setting up Twilio account and getting API credentials
If you don’t already have a Twilio account, you will need to create one. Once you have created an account, log in and navigate to the Twilio console. Click on "Get a Trial Number" to get a phone number that you can use to send SMS messages.

Next, you will need to get your Twilio account SID and authentication token. You can find these credentials on the Twilio console dashboard.

Step 3: Installing the Twilio Python library
To interact with Twilio’s API from your FastAPI application, you will need to install the Twilio Python library. You can do this by running the following command:

pip install twilio

Step 4: Setting up FastAPI routes for sending SMS messages
In your main.py file, import the necessary modules and create the FastAPI app instance. Next, create a route that will handle sending SMS messages using Twilio’s API.

from fastapi import FastAPI
from twilio.rest import Client

app = FastAPI()

account_sid = "your_account_sid"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

@app.get("/send_sms/{phone_number}")
def send_sms(phone_number: str):
    message = client.messages.create(
        body="Your OTP code is: 1234",
        from_="your_twilio_phone_number",
        to=phone_number
    )
    return {"message": "SMS sent successfully"}

Replace "your_account_sid", "your_auth_token", and "your_twilio_phone_number" with your Twilio account SID, authentication token, and phone number respectively.

Step 5: Implementing OTP verification
To implement OTP verification, we will generate a random 4-digit code and send it in the SMS message. Users can then enter this code to verify their phone number.

from fastapi import FastAPI, HTTPException
from twilio.rest import Client
import random

app = FastAPI()

otp_codes = {}

@app.get("/send_sms/{phone_number}")
def send_sms(phone_number: str):
    otp_code = random.randint(1000, 9999)
    otp_codes[phone_number] = otp_code

    client.messages.create(
        body=f"Your OTP code is: {otp_code}",
        from_="your_twilio_phone_number",
        to=phone_number
    )
    return {"message": "SMS sent successfully"}

@app.get("/verify_otp/{phone_number}/{otp}")
def verify_otp(phone_number: str, otp: int):
    if phone_number not in otp_codes:
        raise HTTPException(status_code=404, detail="OTP not found")
    if otp == otp_codes[phone_number]:
        del otp_codes[phone_number]
        return {"message": "OTP verification successful"}
    else:
        return {"message": "OTP verification failed"}

Step 6: Running your FastAPI application
To run your FastAPI application, use the Uvicorn ASGI server. Navigate to your project directory in the terminal and run the following command:

uvicorn main:app --reload

Your FastAPI application should now be running on http://127.0.0.1:8000/. You can access the /send_sms and /verify_otp routes to send SMS messages and verify OTP codes.

That’s it! You have successfully created a FastAPI web application that allows users to send SMS messages for OTP verification using Twilio’s API. Feel free to customize the functionality further and add additional features as needed.

0 0 votes
Article Rating

Leave a Reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@sanga_tamizhan
5 hours ago

To run the OTP verification code, it seems necessary to buy an American phone number in Twilio for sender.

1
0
Would love your thoughts, please comment.x
()
x