Skip to main content

FastAPI Tutorial for Beginners: Build Your First API with CORS and Uvicorn

 

FastAPI is amazing! You can create APIs using FastAPI very quickly. With these APIs, you can connect the backend to the frontend. You can access user data through the API and process it on a Uvicorn server. 

Here is an example of a FastAPI app you can start with

from fastapi import FastAPI

from fastapi.middleware.cors import CORSMiddleware


app = FastAPI()


# CORS setup

app.add_middleware(

    CORSMiddleware,

    allow_origins=["*"],  # Consider restricting this in production

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"],

)



# Root route

@app.get("/")

def root():

    return {"message": "Welcome to the fastAPI"}


How to Run It

Go to the project or file directory and run the command:
uvicorn main:app --reload

Output 

You will see output like this at the URL: http://localhost:8000/



In the code, we are using CORS middleware to allow connections between different platforms, such as the frontend and backend.
You can specify your frontend website in the code (e.g., www.salimwireless.com) so that the backend only processes requests coming from that domain. This is a good practice for production environments

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

app = FastAPI()

# CORS setup
app.add_middleware(
    CORSMiddleware,
    allow_origins=["www,salimwireless.com"],  # Consider restricting this in production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# Root route
@app.get("/")
def root():
    return {"message": "Welcome to the fastAPI"}

Further Reading 

Contact Us

Name

Email *

Message *