Test FastAPI Endpoint CORS Locally: 2 Steps Guide

Test FastAPI Endpoint CORS Locally: 2 Steps Guide

Cross-Origin Resource Sharing (CORS) can be a challenge when developing APIs locally.

In this article, we’ll explore how to configure and test CORS for FastAPI endpoints on localhost.

Test FastAPI Endpoint CORS Locally

CORS restrictions (including allowed_origin and allowed_methods) do not work if we are calling API endpoints from the same origin.

Calling localhost APIs from local Postman and Swagger is considered as the same origin.

To test the CORS restrictions, set up two different origins for the backend (FastAPI application) and the front end. You can do that by running two applications with two different ports.

Follow the steps below.

Backend: FastAPI Application

Sample FastAPI code with get and post endpoint.

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Allow frontend origin (adjust as necessary)
origins = [
    "http://127.0.0.1:3001",  # Localhost development server for the frontend
    "http://localhost:3001",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["GET"],  # Specify allowed HTTP methods
    allow_headers=["*"],
)

@app.get("/post/")
async def process_get():
    return {"message": "This endpoint only allows GET"}

@app.post("/post/")
async def process_post():
    # Explicitly raise an error to prevent POST usage
    raise HTTPException(status_code=405, detail="Method not allowed")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Run FastAPI backend using unicorn.

uvicorn main:app --reload

It starts the FastAPI server.

Access the Swagger document by opening the URL in the browser tab.

http://127.0.0.1:8000

Frontend: To Test CORS Middleware

Save the code below as index.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CORS Test</title>
</head>
<body>
    <h1>Testing CORS with FastAPI</h1>
    <button id="testPost">Test POST Request</button>

    <script>
        document.getElementById("testPost").addEventListener("click", async () => {
            try {
                const response = await fetch("http://localhost:8000/post/", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({ value: "Hello from frontend" }), // Match Pydantic model
                });

                if (response.ok) {
                    const data = await response.json();
                    console.log("Response:", data);
                    alert("Response received: " + JSON.stringify(data));
                } else {
                    console.error("Request failed with status:", response.status);
                    const errorMessage = await response.text();
                    alert("Error: " + errorMessage);
                }
            } catch (error) {
                console.error("Error:", error);
                alert("An error occurred. Check the console for details.");
            }
        });
    </script>
</body>
</html>

Run the below command to start the frontend server.

python -m http.server 3001

Access the frontend application by opening the below URL in the browser tab.

http://127.0.0.1:3001

You can see the “Test POST Request” button. By clicking on the button, you can call the FastAPI backend endpoint API and test the CORS middle including allowed_origin and allowed_method. origin.

You can tweak the front end and backend code to test the different HTTP methods (like GET, POST, PUT) or different allowed origin.

Hope this guide to test FastAPI endpoint CORS locally helps you. If you have any questions, let’s discuss.

Leave a Reply

Your email address will not be published. Required fields are marked *