> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Introduction to FastAPI: Install and Run Your First API

> Discover what FastAPI is, why it's one of Python's fastest frameworks, and how to write and run your very first application in minutes.

Now that you understand how the web works, it's time to meet **FastAPI** — one of the most popular, modern, and high-performance Python frameworks for building APIs. FastAPI was designed to feel natural to Python developers by leaning on standard type hints, and it rewards that familiarity with automatic data validation, interactive documentation, and async support right out of the box. In this lesson, you'll install it, write your first application, and have a running server in under five minutes.

***

## What is FastAPI?

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python based on standard Python type hints. It was created by Sebastián Ramírez and is widely adopted in production systems across the industry.

### Key Features

* **🚀 High Performance:** Built on Starlette and Pydantic, making it one of the fastest Python frameworks — on par with Node.js and Go.
* **✍️ Faster Coding:** Speeds up feature development by 200–300% thanks to automatic validation and documentation.
* **🛡️ Fewer Bugs:** Reduces developer-introduced errors by approximately 40% through automatic input validation.
* **📖 Auto-Generated Documentation:** Generates interactive Swagger UI and ReDoc documentation pages automatically from your code.
* **🔒 Modern & Async:** Native support for asynchronous programming (`async`/`await`) out of the box.

***

## The Tech Stack Under the Hood

FastAPI doesn't do everything alone — it coordinates three powerful components:

```mermaid theme={null}
graph TD
    Client[Client Browser/App] --> Uvicorn[Uvicorn ASGI Server]
    Uvicorn --> FastAPI[FastAPI App Framework]
    FastAPI --> Starlette[Starlette: Routing & Web Parts]
    FastAPI --> Pydantic[Pydantic: Data Validation & Serialization]
```

* **Uvicorn:** An ASGI (Asynchronous Server Gateway Interface) web server. It receives incoming TCP connections from clients and forwards them to FastAPI.
* **Starlette:** A lightweight ASGI framework toolkit. FastAPI inherits all of its routing, middleware, and web-handling capabilities from Starlette.
* **Pydantic:** The data validation and serialization library. It enforces types, converts compatible data, and generates error messages automatically.

<Note>
  When you run `uvicorn main:app --reload`, Uvicorn is the process listening on port 8000. Starlette handles routing, and Pydantic validates every request and response your code touches.
</Note>

***

## Installation

<Steps>
  <Step title="Create and activate a virtual environment">
    ```bash theme={null}
    python -m venv .venv
    ```

    <Tabs>
      <Tab title="macOS / Linux">
        ```bash theme={null}
        source .venv/bin/activate
        ```
      </Tab>

      <Tab title="Windows">
        ```bash theme={null}
        .venv\Scripts\activate
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Install FastAPI and Uvicorn">
    <Tabs>
      <Tab title="pip">
        ```bash theme={null}
        pip install fastapi uvicorn
        ```
      </Tab>

      <Tab title="uv (faster)">
        ```bash theme={null}
        uv pip install fastapi uvicorn
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Verify the installation">
    ```bash theme={null}
    pip show fastapi
    pip show uvicorn
    ```
  </Step>
</Steps>

***

## Writing Your First App

Create a file named `main.py` — this will serve as the entry point for your **Employee Management System (EMS)** application:

```python theme={null}
# main.py
from fastapi import FastAPI

# Initialize the FastAPI app
app = FastAPI(
    title="Employee Management System API",
    description="A professional API to manage company employees, departments, and communication.",
    version="1.0.0"
)

# Define a root GET endpoint
@app.get("/")
def read_root():
    return {
        "message": "Welcome to the Employee Management System API!",
        "status": "online"
    }

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}
```

### Understanding the Code

Let's break down what each piece does:

**`app = FastAPI(...)`**
Creates the central application object. This object coordinates all routing, middleware, and startup events. Passing `title`, `description`, and `version` automatically populates your Swagger documentation page.

**`@app.get("/")`**
This is a **Path Operation Decorator**. It registers the function below it to handle:

* HTTP method: `GET`
* Path: `/` (the root path)

**`def read_root()`**
The handler function that runs when a user hits this endpoint. FastAPI automatically serializes the returned Python dictionary into a JSON response — you never need to call `json.dumps()` manually.

**`item_id: int`**
FastAPI reads the `{item_id}` from the URL path and automatically converts it to an integer. If someone sends `/items/abc`, FastAPI returns a `422` validation error immediately.

**`q: str | None = None`**
Any parameter that isn't in the path is treated as a query parameter. This one is optional and defaults to `None`.

<Tip>
  Unlike traditional Python programs that run top-to-bottom, a FastAPI application is a **configuration** — you describe what should happen for each route, then Uvicorn waits for requests and FastAPI decides which function to call.
</Tip>

***

## Running the Application

```bash theme={null}
uvicorn main:app --reload
```

| Part       | Meaning                                               |
| ---------- | ----------------------------------------------------- |
| `main`     | Python filename (`main.py`)                           |
| `app`      | The `FastAPI` instance variable name inside that file |
| `--reload` | Restart server automatically when you save changes    |

Once running, you'll see output like this:

```text theme={null}
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [48392] using WatchFiles
INFO:     Application startup complete.
```

***

## Accessing Your Application

Open your browser and visit the following URLs:

| URL                                  | Purpose                                         |
| ------------------------------------ | ----------------------------------------------- |
| `http://127.0.0.1:8000`              | Your running API                                |
| `http://127.0.0.1:8000/docs`         | **Swagger UI** — interactive testing playground |
| `http://127.0.0.1:8000/redoc`        | **ReDoc** — clean, structured documentation     |
| `http://127.0.0.1:8000/openapi.json` | Raw OpenAPI specification                       |

Visiting `http://127.0.0.1:8000/` should return:

```json theme={null}
{
  "message": "Welcome to the Employee Management System API!",
  "status": "online"
}
```

***

## Execution Flow

Here is how a request moves through your FastAPI application from start to finish:

```text theme={null}
Start Application
        │
        ▼
Create FastAPI App
        │
        ▼
Register Endpoints
        │
        ▼
Start Uvicorn Server
        │
        ▼
Wait for Client Requests
        │
        ▼
Request Received
        │
        ▼
Find Matching Endpoint
        │
        ▼
Execute Handler Function
        │
        ▼
Convert Response to JSON
        │
        ▼
Send Response to Client
```

<Note>
  Your handler functions are **never called directly by you**. FastAPI calls them automatically when a matching request arrives — this is the Inversion of Control (IoC) pattern in action, which you'll explore in depth in the Dependency Injection lesson.
</Note>
