Creating Routes

Follow the steps below to create custom API routes for your FastAPI application. Use the interactive API request tool to practice and test your routes.

  1. Start by defining a new route in your main.py file. Use the @app.method decorator, where method can be GET, POST, PUT, DELETE, PATCH, etc.
  2. Add a function that handles the request for the route. The function name should be descriptive of the action it performs.
  3. Test the new route using the interactive API request tool below by selecting the HTTP method, setting parameters, and adding a request body if necessary.

Using the Interactive API Request Tool

Step 1: Select HTTP Method

Choose the HTTP method you want to test from the dropdown menu. The available methods are GET, POST, PUT, DELETE, and PATCH.

Step 2: Set Parameters

If your selected method requires parameters (e.g., GET, PUT, DELETE, PATCH), enter the ID value in the input field. For example, if you're testing a GET request to retrieve a CEO by ID, enter the ID value.

Step 3: Add Request Body (if applicable)

For methods that require a request body (e.g., POST, PUT, PATCH), you can enter a custom body by typing in the body content. The body should be in JSON format.

Step 4: Execute the Request

Click the "Execute" button to send the request to the server. If the request is successful, the response will be displayed below. If there is an error, the error message will be shown instead.

Loader Animation

When you click "Execute", a loader animation will appear indicating that the request is being processed. The loader will disappear once the request is complete, and the response will be displayed.

Method Instructions:

POST Method

The POST method is used to create a new resource on the server. When using POST, you need to define a route and a function that handles the creation of the resource.

@app.post("/ceos")
def create_ceo(ceo: schemas.CEOCreate, db: Session = Depends(get_db)):
    return crud.create_ceo(db=db, ceo=ceo)

Api Response:

Request Details:

fetch("https://fast-api-tutorial-backend.vercel.app/ceos", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: {
  "name": "John Doe",
  "company": "Example Corp"
}
});

API Route:

@app.post("/ceos")
def post_ceo(ceo_id: int):
    return post_ceo