Search⌘ K
AI Features

Creating Our First App Using FastAPI

Discover how to create a basic FastAPI application by importing the FastAPI class, defining routes, and handling GET requests. Explore various HTTP operations including POST, PUT, and DELETE methods to manage routes effectively. This lesson equips you with the skills to build and run simple RESTful APIs on your local machine using FastAPI.

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"}
Simple app using FastAPI

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. This app is the same one called by uvicorn in the above terminal.

  • In line 5, we create a GET path/route. This is the default route or the route after /. For example, in a URL like https://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 call uvicorn like 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 a POST manner.
    • @app.put() can be used if we want the client application to access the route in a PUT manner.
    • @app.delete() can be used if we want the client application to access the route in a DELETE manner.

    There are four more operation types that could also be used. They are @app.options(), @app.head(), @app.patch(), and @app.trace().