...
/Creating Our First App Using FastAPI
Creating Our First App Using FastAPI
Get started with creating your first app using FastAPI.
We'll cover the following...
Creating a simple FastAPI app
Let’s now create a basic FastAPI application.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello World"}Explanation
To learn how to execute the FastAPI application on your local machine, refer to the Appendix section.
-
In line 1, we import the
FastAPI, which is a Python class that provides all the functionality for the API. -
In line 3, we create an instance of the class FastAPI and name it
app. Thisappis the same one called byuvicornin the above terminal. -
In line 5, we create a
GETpath/route. This is the default route or the route after/. For example, in a URL likehttps://example.com/items/foo, the path would be/items/foo. -
In line 6, we define the function that will be executed whenever someone visits the above-mentioned route.
-
In line 7, we finally return a response to the client whenever this route is accessed.
Points to remember
-
If we create our app like this:
my_awesome_api = FastAPI()And put it in a file
main.py, then you would calluvicornlike this:uvicorn main:my_awesome_api --reload -
We can also use the other operations instead of
GET:@app.post()can be used if we want the client application to access the route in aPOSTmanner.@app.put()can be used if we want the client application to access the route in aPUTmanner.@app.delete()can be used if we want the client application to access the route in aDELETEmanner.
There are four more operation types that could also be used. They are
@app.options(),@app.head(),@app.patch(), and@app.trace().