Defining the Root Endpoint
Defining the Root Endpoint in FastAPI
In this lesson, you will learn how to define the most basic endpoint (the root) in a FastAPI application. Our goal is for you to understand how to create a root endpoint that responds with a simple JSON message. By the end, you should be able to implement and test a basic root endpoint in FastAPI.
What is an Endpoint?
An endpoint is a specific URL path where a client can send requests to a server. Think of it as a web address that leads to a specific resource or action on the server. Endpoints are essential in web APIs as they define where and how the server should respond to requests.
For example, an endpoint can be a URL like /users to get user information or /products to retrieve product details. Each endpoint can support different HTTP methods (like GET, POST, PUT, DELETE) to perform various actions.
What are HTTP Methods?
HTTP methods indicate the desired action to be performed for a given resource.
Common methods include:
- GET: Retrieves data from the server.
- POST: Sends data to the server to create a new resource.
- PUT: Updates an existing resource on the server.
- DELETE: Removes a resource from the server.
The Root Endpoint
A root endpoint is typically the entry point to your API, defined at the path "/". It commonly uses the GET method to provide a welcome message or basic information about the API, serving as the initial access point for users.
Let's see how we implement it!
Getting our FastAPI Ready
As you've seen in the past lessons, we begin by importing the FastAPI class from the fastapi module and creating an instance of FastAPI:
This instance will be used to define our endpoints.
Defining a GET Method for the Root Endpoint
To define an endpoint in FastAPI, decorators are used to associate a specific path with a function that handles the requests. Here, we use the @app.get("/") decorator to set up a root endpoint that handles GET requests at the path "/":
