Path Operations

from fastapi import FastAPI

# Defining the FastAPI() function
app = FastAPI()

# You need to use a decorator to "activate" the FastAPI logic
# Otherwise it's just a plain python function
@app.get("/") # This is a http method (GET)

# The function itself
def root():

# In true pythonic fashion, function will return result
    return {"message": "Hello World"}
  • Decorator:

@app
  • Method:

.get
  • Path:

("/") # Root path

Note: If you make changes to the code, pass in the --reload flag to the uvicorn webserver so it restarts automatically

uvicorn main:app --reload

Use this only for the development environment

Example of New Path Operation:

# New Path Operation
@app.get("/posts")
def get_posts():
    return {"data": "This is your post"}

The code will go down the list of paths and find the first one that matches the URL pattern

For Example:

@app.get("/")
def root():
    return {"message": "Hello World"}
    
@app.get("/")
def get_posts():
    return {"data": "This is your post"}
  • Note that both have the same path ("/")

  • Once this goes down the list it will find the root function first

  • It will return the first message:

{"message": "Hello World"}

So what it looks for is as follows:

  • Request GET method

  • With the URL: "/"

THE ORDER IN WHICH YOU STRUCTURE YOUR ROUTES/PATH OPERATIONS DOES MATTER!

IT WILL DETERMINE HOW YOUR API WORKS

Resources:

  • If you don't know which method to use, click here for HTTP Methods

Last updated