DEV Community

Cover image for How to make an API using FastAPI
Gourav Singh Rawat
Gourav Singh Rawat

Posted on

How to make an API using FastAPI

Let’s see how we can create a basic API using the FastAPI framework.

First, make sure you have FastAPI and Uvicorn installed. You can install them using:

As the FastAPI documentation suggests you'll need Uvicorn and FastAPI installed you can do so by:

pip install fastapi uvicorn[standard]
Enter fullscreen mode Exit fullscreen mode

Now, let’s create a simple FastAPI application where we’ll be setting up our FastAPI app. Create a file named main.py:

# main.py
from fastapi import FastAPI

app = FastAPI()
Enter fullscreen mode Exit fullscreen mode

But that’s not all we’re just initializing our FastAPI instance, now we also need to setup something known as CORS (Cross-Origin Resource Sharing).

CORS is important when you want to allow your API to be accessed by web applications from different origins. Modify your main.py file.

# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Configure CORS

origins = ["http://localhost", "http://localhost:3000", "https://yourfrontenddomain.com"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Enter fullscreen mode Exit fullscreen mode

Replace the allowed origins (origins) with the actual domains of your front-end applications. Or if you’re just testing your app on localhost then you might not need to change much…

Make an API.

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}
Enter fullscreen mode Exit fullscreen mode

Your file should look like this.

# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Configure CORS

origins = ["http://localhost", "http://localhost:3000", "https://yourfrontenddomain.com"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}
Enter fullscreen mode Exit fullscreen mode

Call your API of endpoint /. But before that we’ll need to start running the server. Now use the Uvicorn to initiate the FastAPI server.

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

This will start the FastAPI development server, and your API will be accessible at http://127.0.0.1:8000. The CORS middleware will allow requests from the specified origins.

You can access the API by opening your browser or using a tool like curl or Postman. For example, if you’re running it locally, open http://localhost:8000 in your browser, and you should see the “Hello, World!” message.

Hope this was useful. Thanks for reading.

Top comments (0)