FastAPI - Beginner to Pro / FastAPI Setup & Installation

Virtual Environment Overview

🐍 Virtual Environment

A Virtual Environment (venv) is an isolated Python environment that allows you to install packages separately for each project.

It ensures that project dependencies do not conflict with each other.

πŸ€” Why Do We Need It?

Imagine:

  • Project A needs Django 3.2

  • Project B needs Django 4.2

Without a virtual environment:

  • Both versions would clash globally.

With a virtual environment:

  • Each project has its own isolated package version.

🧠 Key Benefits

  • βœ… Dependency isolation

  • βœ… Avoid version conflicts

  • βœ… Clean global Python installation

  • βœ… Easier deployment

  • βœ… Reproducible environments

πŸ—οΈ How It Works

Each virtual environment contains:

  • A separate Python interpreter

  • Its own site-packages folder

  • Independent installed libraries

When activated:

  • Python uses packages inside that environment

  • Global packages are ignored (unless allowed)


βš™οΈ Setting Up a Virtual Environment

Python provides a built-in module called venv.

πŸͺŸ Step 1: Create a Virtual Environment

Inside your project folder:

πŸ’» Windows

python -m venv venv

🍎 macOS / Linux

python3 -m venv venv

Here:

  • -m venv β†’ tells Python to create a virtual environment

  • venv β†’ name of the environment folder (you can rename it)

Example:

python3 -m venv myenv

▢️ Step 2: Activate the Virtual Environment

πŸ’» Windows

venv\\Scripts\\activate

🍎 macOS / Linux

source venv/bin/activate

After activation, your terminal will show:

(venv)

That means it is active.

If your virtual environment is named myenv, then you should activate it using:

source myenv/bin/activate
OR
myenv\\Scripts\\activate

⏹️ Step 3: Deactivate

deactivate

This returns you to the global Python environment.


πŸ“ Recommended Project Structure

project/
β”‚
β”œβ”€β”€ venv/
β”œβ”€β”€main.py
β”œβ”€β”€ requirements.txt