In this article, you’ll learn how to set up a FastAPI project and run a simple web server. For a complete understanding, it’s recommended to review the FastAPI documentation and its introductory tutorial before you begin.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Installing FastAPI and Optional Dependencies
FastAPI can be easily installed via pip. It is recommended to install FastAPI with all its optional dependencies as they can be very useful when your project scales. Run the following command to install:pip freeze, you’ll see FastAPI along with its bundled optional dependencies, which may include GraphQL support, websockets, and more:
If you’re curious about the package code, you can find all installed packages within the
lib folder of your virtual environment.Creating a Basic FastAPI Application
After installing FastAPI, create a new Python file (e.g.,main.py). In this file, import FastAPI and instantiate an application object named app following the documentation conventions:
/) that returns a JSON response with a message saying “Hello World”. Remember to save your file after making changes. If your editor prompts you regarding auto-formatting (for instance, PEP8 compliance), it’s good practice to allow the change.
Running the Server
Once your FastAPI application is ready, you can start the server using Uvicorn. Since you’ve installed FastAPI with the[all] flag, Uvicorn is already available. Activate your virtual environment and run:
main: The name of your Python file (without the.pyextension).app: The FastAPI instance to be served.--reload: Automatically reloads the server when code changes are detected.
Summary
In this lesson, you learned to:- Install FastAPI along with optional dependencies using the
[all]flag. - Create a basic FastAPI application that provides a “Hello World” JSON response.
- Run the FastAPI server with Uvicorn and observe its output.
In the next section, we will explore each component of the code in more detail to understand the underlying functionality better.