green snake
Photo by Pixabay on Pexels.com

【Complete Guide】Getting Started with FastAPI in a venv — From Environment Setup to Verification


📋 Article Highlights (Summary)

  • Who Is This For?
    Beginners to intermediate Python developers who know the basics of Python but have never used a web framework
  • What You Will Learn
    1. Benefits of virtual environments (venv) and how to create one
    2. How to check and switch your Python version
    3. Installation steps for FastAPI itself and the ASGI server (Uvicorn)
    4. Running and verifying a minimal “Hello, World!” API
    5. Accessibility considerations: annotated commands and highly readable, color‐blind–friendly code
  • What You’ll Gain
    • A clean development environment that won’t affect other projects
    • A solid foundation for understanding FastAPI’s basic structure and moving on to routing or database integration

🎯 Target Audience

  • Developers comfortable with general Python programming but new to frameworks
  • Anyone who wants to try a new library without polluting their existing Python setup
  • Those who need a clear, step‐by‐step walk-through of FastAPI installation

♿ Accessibility Level

  • Readability: Balanced use of kanji, hiragana, and katakana; ruby text examples where needed
  • Structure: Plenty of headings and lists to ensure logical flow for screen readers
  • Code Examples: Commented and formatted with high-contrast, color-blind–friendly styling
  • Summaries: Key takeaways at the end of each section for easy review

1. Introduction: Why Use venv?

In web app development, dependency version conflicts often arise across multiple projects.
By using venv (virtual environment), you can create an isolated Python environment for each project.

  • Benefits
    • Does not affect the system Python
    • Simplifies project-specific package management
    • Improves environment reproducibility in team settings

2. Checking and Preparing Your Python Version

2.1 Verify Python Version

Run the following in your terminal/command prompt to ensure you have Python 3.8 or higher:

python3 --version
# e.g.: Python 3.10.6

If it’s below 3.8, download and install the latest version from https://python.org.

2.2 Optional: Version Management with pyenv

To switch between multiple Python versions, pyenv is helpful. Install as follows:

# On macOS/Linux
curl https://pyenv.run | bash
# After reloading your shell
pyenv install 3.10.6
pyenv global 3.10.6

Once python3 --version shows 3.10.6, you’re ready.


3. Creating a Virtual Environment with venv

3.1 Create Your Project Folder

Navigate to your desired directory and make a project folder:

mkdir fastapi-venv-project
cd fastapi-venv-project

3.2 Create the venv

Use Python’s built-in venv module:

python3 -m venv .venv
  • .venv is a common convention; you can choose another name, but hidden folders are typical.

3.3 Activate / Deactivate the venv

  • Activate
    • macOS/Linux:
      source .venv/bin/activate
      
    • Windows (PowerShell):
      .\.venv\Scripts\Activate.ps1
      
  • Deactivate
    deactivate
    

When activated, your prompt will show (.venv).


4. Installing FastAPI and Uvicorn

4.1 Upgrade pip

Ensure you’re using the latest pip:

pip install --upgrade pip

4.2 Install FastAPI

pip install fastapi

FastAPI is a modern framework that leverages type hints and auto-generates documentation.

4.3 Install the ASGI Server (Uvicorn)

FastAPI requires an ASGI server to run. Uvicorn is fast and lightweight:

pip install "uvicorn[standard]"
  • The [standard] extra installs recommended dependencies like httptools and uvloop.

5. Running a “Hello, World!” API

5.1 Create Sample Code

In your project root, create main.py with:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    """
    Handles GET requests to the root path.
    """
    return {"message": "Hello, World!"}

5.2 Start the Server

uvicorn main:app --reload
  • main:app refers to the app instance in main.py.
  • --reload auto-restarts on code changes (development only).

5.3 Verify Operation

Access via browser or curl:

# In your terminal
curl http://127.0.0.1:8000/
# Should return {"message":"Hello, World!"}

You can also view the auto-generated docs:


6. Common Issues and Solutions

Issue Solution
command not found: python3 Python isn’t installed or not in your PATH. Try python --version too, and reinstall if needed.
Permission denied You may need admin rights to create the venv. Use sudo or check folder permissions.
Port conflict when starting Uvicorn Port 8000 is in use by another process. Specify a different port, e.g., --port 8001.
ModuleNotFoundError: fastapi Your venv may not be activated. Check with which python and pip list.

7. Next Steps

  1. Add Routing
    Learn about path and query parameters.
  2. Data Validation with Pydantic Models
    Enforce type safety for input/output.
  3. Database Integration
    Implement CRUD with SQLAlchemy or Tortoise ORM.
  4. Authentication & Authorization
    Design secure APIs with OAuth2 or JWT.

✨ Conclusion

This guide walked you through installing FastAPI in a venv, upgrading pip, adding FastAPI and Uvicorn, and running a minimal “Hello, World!” API.

  • Create and activate a venv to avoid environment pollution
  • Upgrade pip → install FastAPI/Uvicorn → verify operation

Now you have a solid FastAPI foundation. Next, dive into routing, database integration, and authentication to build real-world APIs!


If you have any questions, feel free to leave a comment below.

By greeden

Leave a Reply

Your email address will not be published. Required fields are marked *

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)