DEV Community

Saras Growth Space
Saras Growth Space

Posted on Edited on Fully Autonomous

Building a Production-Oriented Weather API with FastAPI – Project Structure and Environment Setup

Part 2 of our FastAPI Weather API series

In the previous article, we explored the architecture of our Weather API project and discussed how to organize a FastAPI application beyond a simple collection of endpoints.

In this article, we'll move from architectural planning to the actual project foundation.

Before writing application code, we need two things in place:

  1. A well-defined project structure.
  2. A reproducible Python development environment.

We'll walk through the decisions, setup steps, commands, and reasoning behind them.

Our goal is not just to make a FastAPI application run. We want to establish a foundation that can support testing, external API integrations, error handling, observability, and future production requirements.


1. Project Overview

We're building a Weather API using FastAPI and Open-Meteo.

Open-Meteo provides two APIs that will form the foundation of our application:

  • Geocoding API: Converts a location or city name into geographic coordinates.
  • Forecast API: Retrieves weather information using latitude and longitude.

Our planned API endpoints are:

Endpoint Responsibility
GET /health Check application health
GET /api/v1/locations/search Search for locations
GET /api/v1/weather/current Retrieve current weather
GET /api/v1/weather/forecast Retrieve weather forecasts

We'll develop these endpoints incrementally rather than implementing everything at once.

2. Task 1 – Designing the Project Structure

Before creating files, we first defined how responsibilities should be separated.

A common beginner approach is to place everything inside a single main.py file. This is convenient for a small demonstration, but it becomes difficult to maintain as the application grows.

For our project, we chose a layered structure that separates:

  • API routing and HTTP concerns
  • Application services
  • Domain models and interfaces
  • External API integrations
  • Configuration and infrastructure
  • Error handling
  • Observability
  • Tests

2.1 Our planned directory structure

The following is the target structure for the project. We'll introduce and implement these components progressively as the relevant milestones arrive.

weather-service/
│
├── app/
│   ├── main.py
│   │
│   ├── api/
│   │   ├── router.py
│   │   ├── dependencies/
│   │   │   └── weather.py
│   │   ├── routers/
│   │   │   └── health.py
│   │   └── v1/
│   │       ├── router.py
│   │       └── routers/
│   │           ├── weather.py
│   │           └── locations.py
│   │
│   ├── middleware/
│   │   ├── request_context.py
│   │   └── request_logging.py
│   │
│   ├── core/
│   │   ├── config.py
│   │   ├── lifespan.py
│   │   └── logging.py
│   │
│   ├── schemas/
│   │   ├── requests/
│   │   │   └── weather.py
│   │   ├── responses/
│   │   │   ├── weather.py
│   │   │   ├── location.py
│   │   │   └── common.py
│   │   └── errors.py
│   │
│   ├── domain/
│   │   ├── models/
│   │   │   ├── weather.py
│   │   │   └── location.py
│   │   ├── interfaces/
│   │   │   └── weather_provider.py
│   │   └── exceptions/
│   │       └── weather.py
│   │
│   ├── services/
│   │   ├── weather_service.py
│   │   └── location_service.py
│   │
│   ├── integrations/
│   │   └── open_meteo/
│   │       ├── provider.py
│   │       ├── geocoding_client.py
│   │       ├── forecast_client.py
│   │       ├── schemas/
│   │       │   ├── geocoding.py
│   │       │   └── forecast.py
│   │       ├── mapper.py
│   │       └── exceptions.py
│   │
│   ├── exceptions/
│   │   ├── application.py
│   │   └── handlers.py
│   │
│   └── observability/
│       ├── instrumentation.py
│       ├── metrics.py
│       └── tracing.py
│
├── tests/
│   ├── unit/
│   ├── integration/
│   └── contract/
│
├── .env.example
├── .gitignore
├── .python-version
├── pyproject.toml
├── uv.lock
├── README.md
├── Dockerfile
└── docker-compose.yml
Enter fullscreen mode Exit fullscreen mode

Some files and folders in this structure are planned for later milestones. We are not creating every file immediately.

2.2 Why did we choose this structure?

Let's understand the purpose of the major directories.

app/api/ – API layer

This is where FastAPI routers and dependencies live.

We separated the health endpoint from the versioned API:

  • api/routers/health.py contains the health-check endpoint.
  • api/v1/routers/weather.py contains weather-related endpoints.
  • api/v1/routers/locations.py contains location-search endpoints.
  • api/v1/router.py combines the version 1 routers.
  • api/router.py combines the health router and versioned API router.

This gives us a clean place to introduce future API versions.

app/api/dependencies/ – Reusable dependencies

FastAPI dependencies allow us to provide initialized services and other reusable components to endpoints.

For example, an endpoint shouldn't need to construct a new weather provider every time it receives a request.

Dependencies help us manage these objects and make testing easier.

app/core/ – Application configuration and infrastructure

This directory contains application-wide configuration:

  • config.py – Application settings.
  • lifespan.py – Startup and shutdown resource management.
  • logging.py – Logging configuration.

For example, we'll eventually use the application lifespan to initialize and close a shared HTTP client.

app/schemas/ – Public API contracts

Schemas define the structure of data entering and leaving our API.

We separated request schemas from response schemas because they serve different purposes.

We also included errors.py to define the structure of our API error responses.

An important distinction: this file defines the response format for errors. It does not contain all application exceptions or their handling logic.

app/domain/ – Core application concepts

The domain layer contains application-level concepts independent of the external weather provider.

It includes:

  • Models representing weather and location information.
  • Interfaces describing the expected behavior of a weather provider.
  • Domain exceptions representing meaningful application problems.

This separation helps prevent our business logic from becoming tightly coupled to Open-Meteo.

app/services/ – Application operations

Services coordinate application operations.

For example, a weather service might coordinate a provider call, process the returned data, and prepare the result for the API layer.

The router should handle HTTP concerns, not implement the entire weather retrieval workflow.

app/integrations/open_meteo/ – External provider integration

This directory contains everything specific to Open-Meteo.

We separated geocoding and forecast clients because they communicate with different external API endpoints.

The provider adapter exposes a consistent interface to the rest of our application.

The mapper translates provider-specific responses into our internal representations.

This means that if we introduce another weather provider in the future, we won't need to redesign the entire application.

app/exceptions/ – Application-level error handling

This directory contains application exceptions and FastAPI exception handlers.

The handlers will translate internal errors into appropriate HTTP status codes and the public error response format defined in schemas/errors.py.

For example:

  • A location that cannot be found may become HTTP 404.
  • Invalid input may become HTTP 422.
  • An upstream provider timeout may become HTTP 504.

The exact mapping will depend on the semantics of each error.

app/middleware/ – Cross-cutting HTTP concerns

Middleware is useful for functionality that applies across HTTP requests.

We'll use this area for request context and request logging.

app/observability/ – Monitoring and diagnostics

Observability helps us understand how the application behaves.

We have reserved space for:

  • Instrumentation
  • Metrics
  • Distributed tracing

These concerns will be introduced when the application reaches the relevant development stage.

tests/ – Testing

We divided tests into three categories:

  • unit/ – Test individual functions and components.
  • integration/ – Test interactions between application components.
  • contract/ – Verify that external and public API contracts are respected.

This separation helps us organize tests as the project grows.

2.3 Why don't we have a repositories directory?

A repository layer is commonly used when an application works with databases or persistent storage.

Our current application retrieves weather information from an external API. Calling an external API is not automatically a repository operation.

We therefore chose not to introduce a repositories/ directory prematurely.

If we introduce database-backed functionality later, we can add the appropriate abstraction then.

2.4 Why do we have two schema locations?

This is an important architectural distinction.

We have:

  1. app/schemas/
  2. app/integrations/open_meteo/schemas/

They serve different purposes.

Our application schemas define the contracts exposed by our own Weather API.

Open-Meteo schemas describe the response formats returned by the external provider.

We shouldn't expose the external provider's response structure directly as our public API contract.

Keeping these schemas separate gives us control over our own API, even if the external provider changes its response format.

2.5 Python packages and __init__.py

For directories intended to be regular Python packages, we'll include __init__.py files.

Initially, these files can remain empty.

Python also supports namespace packages, which don't require __init__.py. However, namespace packages are useful for specific packaging scenarios and aren't necessary for our application.

For this project, regular packages provide a straightforward and predictable structure.

We'll use absolute imports and run the application from the project root.


3. Task 2 – Setting Up the Python Development Environment

With the architecture planned, we can establish our development environment.

Our actual development setup is:

Component Choice
Operating system Windows
IDE Visual Studio Code
Python 3.14
Shell PowerShell
Virtual environment .venv
Project/dependency manager uv
Web framework FastAPI

We chose Python 3.14 for this project. Dependency compatibility is important, so we should verify that the packages we use support the selected Python version.

3.1 Verify Python installation

First, open the project folder in VS Code.

Open the integrated terminal and select PowerShell.

Verify the installed Python version:

python --version
Enter fullscreen mode Exit fullscreen mode

Check which Python executable is being used:

where.exe python
Enter fullscreen mode Exit fullscreen mode

This helps confirm that the terminal is resolving the expected Python installation.

3.2 Create a virtual environment

A virtual environment isolates project dependencies from other Python projects on the same machine.

This is important because different projects may require different versions of the same package.

We created the virtual environment using VS Code.

Our environment directory is:

.venv/
Enter fullscreen mode Exit fullscreen mode

After creation, we verified that it was activated and that the expected Python executable was being used.

Useful verification commands:

$env:VIRTUAL_ENV
python --version
python -m pip --version
Enter fullscreen mode Exit fullscreen mode

The VIRTUAL_ENV variable should point to the project's .venv directory when the environment is activated.

The Python and pip commands should resolve to the environment's executables.

3.3 Why use a virtual environment?

Without an isolated environment, installing a package for one project can affect another project.

For example:

  • Project A may require one version of HTTPX.
  • Project B may require a different version.
  • Installing both globally can create dependency conflicts.

A virtual environment keeps their dependencies separate.

We will also make sure that .venv is excluded from Git because it is a local development environment, not source code.


4. Understanding uv and Uvicorn

One of the important decisions in our setup was choosing uv.

There is a common source of confusion here: uv and Uvicorn are different tools.

uv is a Python project and package manager. We use it to manage dependencies, lockfiles, and environment synchronization.

Uvicorn is an ASGI server. It runs our FastAPI application and handles incoming ASGI requests.

They solve different problems, so they are not alternatives to each other.

FastAPI applications commonly use Uvicorn as their ASGI server.

4.1 Installing uv inside our virtual environment

For this project, we decided to keep uv inside the project's .venv rather than install it separately on the machine.

We bootstrapped uv using pip:

python -m pip install uv
Enter fullscreen mode Exit fullscreen mode

Then verified the installation:

uv --version
Enter fullscreen mode Exit fullscreen mode

This is the workflow we chose for our learning project.

General recommendation: It is more conventional to install uv outside the environment it manages, often at the user level. That way, uv remains available even if a project virtual environment is deleted.

Our chosen approach works, but it has a practical limitation: if .venv is deleted, uv must be bootstrapped again before it can be used to recreate the environment.

We'll keep this distinction in mind rather than presenting our choice as the universal recommendation.


5. Configuring pyproject.toml

Python projects need a central place to define project metadata, dependencies, and development-tool configuration.

We use pyproject.toml for this purpose.

Our initial configuration is:

[project]
name = "weather-service"
version = "0.1.0"
description = "A production-oriented weather API built with FastAPI"
requires-python = ">=3.14,<3.15"
dependencies = [
    "fastapi[standard]",
    "httpx",
    "pydantic",
]

[dependency-groups]
dev = [
    "pytest",
    "ruff",
    "uv",
]

[tool.uv]
package = false

[tool.ruff]
line-length = 100
target-version = "py314"

[tool.pytest.ini_options]
testpaths = ["tests"]
Enter fullscreen mode Exit fullscreen mode

Let's understand the important sections.

5.1 Project metadata

[project]
name = "weather-service"
version = "0.1.0"
requires-python = ">=3.14,<3.15"
Enter fullscreen mode Exit fullscreen mode

This defines the project name, version, and supported Python version range.

We explicitly selected Python 3.14 for this project.

5.2 Runtime dependencies

dependencies = [
    "fastapi[standard]",
    "httpx",
    "pydantic",
]
Enter fullscreen mode Exit fullscreen mode

These packages are required by the application at runtime.

FastAPI

Our web framework.

We chose fastapi[standard] instead of declaring FastAPI and Uvicorn separately.

The standard extras provide commonly used FastAPI tooling, including an ASGI server and the FastAPI CLI.

HTTPX

We'll use HTTPX to communicate with Open-Meteo.

It supports synchronous and asynchronous HTTP requests. For our application, we'll use its asynchronous capabilities.

Pydantic

FastAPI uses Pydantic for data validation and serialization.

Although Pydantic is installed as a dependency of FastAPI, our application will use it directly. Explicitly declaring it makes our direct dependency clear.

5.3 Development dependencies

[dependency-groups]
dev = [
    "pytest",
    "ruff",
    "uv",
]
Enter fullscreen mode Exit fullscreen mode

These packages support development rather than application runtime functionality.

  • pytest: Testing framework.
  • Ruff: Linting and formatting.
  • uv: Included in our development environment as part of our chosen setup.

One detail worth remembering: uv is included here because of our specific decision to keep it in .venv. It is not a normal application runtime dependency.

5.4 Why package = false?

[tool.uv]
package = false
Enter fullscreen mode Exit fullscreen mode

Our application is not intended to be distributed as an installable Python library.

We want to run the application directly from the project directory.

This setting tells uv not to install the project itself as a package when synchronizing the environment.

5.5 Ruff configuration

[tool.ruff]
line-length = 100
target-version = "py314"
Enter fullscreen mode Exit fullscreen mode

We configure Ruff to use a line length of 100 characters and target Python 3.14 syntax.

This helps maintain consistent code quality as the project grows.

5.6 Pytest configuration

[tool.pytest.ini_options]
testpaths = ["tests"]
Enter fullscreen mode Exit fullscreen mode

This tells pytest where to look for tests by default.

We have already reserved the tests/ directory in our project structure.


6. Generating the Lockfile and Synchronizing Dependencies

Defining dependencies in pyproject.toml is only part of dependency management.

We also want a lockfile.

A lockfile records the resolved dependency versions so that the environment can be reproduced more consistently.

6.1 Generate uv.lock

From the project root, execute:

uv lock
Enter fullscreen mode Exit fullscreen mode

This generates the uv.lock file.

We should commit this file to Git because it helps other developers reproduce the same resolved dependency environment.

6.2 Synchronize the environment

Next, execute:

uv sync
Enter fullscreen mode Exit fullscreen mode

This synchronizes the project's virtual environment with the dependencies declared in the project configuration and lockfile.

Because we use the dev dependency group, the default development synchronization includes our development tools.


7. Verifying the Environment

After installation, we verify that the expected tools are available.

Run:

uv run python --version
uv run fastapi --version
uv run pytest --version
uv run ruff --version
Enter fullscreen mode Exit fullscreen mode

We can also inspect installed packages:

uv pip list
Enter fullscreen mode Exit fullscreen mode

These checks help confirm that the environment is configured correctly.

At this stage, we have not implemented our API endpoints yet. We have established the project structure and development environment needed to begin application development.


8. Important Project Configuration Files

Our project root contains several configuration and documentation files.

File Purpose
pyproject.toml Project metadata, dependencies, and tool configuration
uv.lock Resolved dependency versions
.python-version Declares the project's intended Python version
.gitignore Defines files and directories Git should ignore
.env.example Documents environment variables the application may require
README.md Project documentation
Dockerfile Planned container build instructions
docker-compose.yml Planned local multi-container configuration

Not every file needs to contain implementation details immediately. Some are included in the target project structure for future milestones.


9. Git and Project Progress

We are developing this project alongside a Git repository.

The intention is to keep meaningful milestones in separate commits rather than wait until the entire application is finished.

For the environment and dependency setup, our commit message is:

chore: configure Python environment and dependencies
Enter fullscreen mode Exit fullscreen mode

Before committing, we should inspect the changes:

git status
git diff
Enter fullscreen mode Exit fullscreen mode

Stage the relevant project files:

git add README.md pyproject.toml uv.lock .python-version .gitignore
Enter fullscreen mode Exit fullscreen mode

Review the staged changes:

git diff --cached
Enter fullscreen mode Exit fullscreen mode

Then commit:

git commit -m "chore: configure Python environment and dependencies"
Enter fullscreen mode Exit fullscreen mode

Finally, verify:

git status
git log -1 --oneline
Enter fullscreen mode Exit fullscreen mode

We should not commit .venv, Python cache files, or local secrets.


10. Task 3 – Git Configuration and Repository Hygiene

With the project structure and Python environment ready, we also need to ensure that our Git repository is configured properly.

We created a GitHub repository using GitHub's standard Python template, which provided us with an initial .gitignore file.

We reviewed it and made a few project-specific decisions.

10.1 What should Git track?

Not everything in a Python project belongs in version control.

We should exclude:

  • .venv/ – Local virtual environment.
  • .env – Local environment variables and secrets.
  • __pycache__/ – Python-generated cache files.
  • .pytest_cache/ – Pytest cache.
  • .ruff_cache/ – Ruff cache.
  • .vscode/ – Local editor configuration in our current setup.

We also made sure that the following files remain eligible for version control:

  • pyproject.toml – Project metadata and dependencies.
  • uv.lock – Resolved dependency versions.
  • .python-version – Selected Python version.
  • .env.example – Example environment configuration without real secrets.
  • README.md – Project documentation.

One important detail: our .gitignore contains commented-out entries for uv.lock and .python-version. Since these entries are commented out, Git does not ignore those files.

10.2 What about the .vscode directory?

VS Code workspace configuration can be useful when working in a team.

However, it can also contain personal settings and machine-specific configuration.

For our current individual development workflow, we decided to ignore the entire .vscode/ directory.

If we later introduce shared workspace settings or recommended extensions, we can selectively commit those files.

10.3 Commit message conventions

We also decided to follow a consistent commit message format.

We'll use the Conventional Commits style:

type: short description

Some common prefixes we'll use:

Prefix Purpose
feat: New functionality
fix: Bug fixes
chore: Project maintenance
docs: Documentation changes
test: Tests
refactor: Code restructuring

Examples:

chore: configure Python environment and dependencies
chore: initialize project structure
chore: update gitignore for local development
docs: update project documentation
feat: add weather forecast endpoint
Enter fullscreen mode Exit fullscreen mode

We are currently committing directly to the main branch. For an individual learning project, this is a reasonable starting point. We can introduce feature branches and pull requests when collaboration or more complex development workflows become relevant.


11. Milestone 1 – Final Verification

Before moving into application development, we reviewed the project foundation.

Our checklist:

  • [x] Designed the application architecture.
  • [x] Defined the directory structure and responsibilities.
  • [x] Selected Python 3.14.
  • [x] Created and verified the .venv environment.
  • [x] Installed and configured uv.
  • [x] Defined runtime and development dependencies.
  • [x] Generated the uv.lock file.
  • [x] Reviewed and customized .gitignore.
  • [x] Established commit message conventions.
  • [x] Updated the project README.
  • [x] Committed the project foundation to GitHub.

At this point, we have completed Milestone 1 – Project Foundation.

We haven't implemented the weather endpoints yet. Instead, we've established the structure and tooling needed to implement them in a maintainable way.


12. What's Next?

With the project foundation ready, we'll move to the next milestone:

Milestone 2 – FastAPI Application Bootstrap

We'll begin implementing the actual application, covering:

  1. Understanding the FastAPI application entry point.
  2. Creating and initializing the FastAPI application.
  3. Registering application routers.
  4. Implementing our first health-check endpoint.
  5. Running the application using Uvicorn.
  6. Exploring Swagger UI and the generated OpenAPI documentation.

This article is part of our ongoing FastAPI Weather API series. The project is being developed incrementally, with architecture, implementation decisions, setup steps, and Git changes documented along the way.

Top comments (0)