Cheatsheets

TOML

TOML

TOML (Tom's Obvious, Minimal Language) is a configuration file format designed to be minimal, readable, and unambiguous. It's commonly used for application configuration, package manifests, and data serialization.

6 Categories 18 Sections 43 Examples
TOML Configuration Data Format Tables Keys Values Data Types Syntax

Getting Started

Fundamental TOML concepts and syntax for beginners.

Basic Syntax

Comments, whitespace, file format, and basic TOML structure.

Simple TOML file with comments

A basic TOML file demonstrating key-value pairs and comment usage.

Code
# This is a comment
title = "My App"
# Comments can be placed anywhere
version = "1.0.0"
Execution
Terminal window
toml-parser config.toml
Output
Terminal window
title: "My App"
version: "1.0.0"
  • Comments start with
  • Whitespace is ignored in most places.
  • Newlines separate key-value pairs.

Multi-line structure with sections

Demonstrates basic section structure and organization.

Code
# Configuration file
name = "MyApp"
# Section for database
[database]
host = "localhost"
port = 5432
Execution
Terminal window
toml-parser config.toml
Output
Terminal window
name: "MyApp"
database:
host: "localhost"
port: 5432
  • Sections are defined with [section_name].
  • Keys within sections are nested under their section.

Data Types

Overview of all TOML data types and their representations.

All primitive data types

Demonstrates each TOML primitive data type with examples.

Code
# String
name = "Alice"
# Integer
count = 42
# Float
pi = 3.14159
# Boolean
enabled = true
# Date
birth = 1990-05-27
# Time
alarm = 15:30:00
# DateTime
created = 2021-12-25T10:30:00Z
Execution
Terminal window
toml-parser types.toml
Output
Terminal window
name: "Alice"
count: 42
pi: 3.14159
enabled: true
birth: 1990-05-27
alarm: 15:30:00
created: 2021-12-25T10:30:00Z
  • TOML supports 7 data types: String, Integer, Float, Boolean, Date, Time, DateTime.
  • Type inference is automatic in TOML.

Arrays and tables

Shows how to define arrays, tables, and arrays of tables.

Code
# Array
colors = ["red", "green", "blue"]
# Nested array
matrix = [[1, 2], [3, 4]]
# Table
[owner]
name = "Bob"
# Array of tables
[[products]]
id = 1
name = "Widget"
Execution
Terminal window
toml-parser complex.toml
Output
Terminal window
colors: ["red", "green", "blue"]
matrix: [[1, 2], [3, 4]]
owner:
name: "Bob"
products: [{ id: 1, name: "Widget" }]
  • Arrays are enclosed in brackets with comma-separated values.
  • Tables group related key-value pairs together.

Key-Value Pairs

Syntax for defining keys and values in TOML documents.

Simple key-value pairs

Demonstrates basic key-value pair syntax with different data types.

Code
name = "Alice"
age = 30
active = true
score = 92.5
Execution
Terminal window
toml-parser simple.toml
Output
Terminal window
name: "Alice"
age: 30
active: true
score: 92.5
  • Keys are case-sensitive.
  • Values must be separated from keys by an equals sign (=).

Quoted and dotted keys

Shows quoted keys and dotted key notation for nesting.

Code
# Quoted key with spaces
"physical address" = "123 Main St"
# Single-quoted key
'special-key' = "value"
# Dotted key (nesting)
database.host = "localhost"
database.port = 5432
database.credentials.user = "admin"
Execution
Terminal window
toml-parser keys.toml
Output
Terminal window
physical address: "123 Main St"
special-key: "value"
database:
host: "localhost"
port: 5432
credentials:
user: "admin"
  • Quoted keys can contain any character.
  • Dotted keys create nested tables automatically.
  • Keys must be unique within their scope.

Bare and quoted key combinations

Combines bare and quoted keys for flexibility in naming.

Code
# Bare key (unquoted)
name = "Project"
# Keys with special characters must be quoted
"api-key" = "secret123"
"version 2.0" = true
# Mixed dotted keys
app.settings."user-preferences" = { theme = "dark" }
Execution
Terminal window
toml-parser mixed.toml
Output
Terminal window
name: "Project"
api-key: "secret123"
version 2.0: true
app:
settings:
user-preferences:
theme: "dark"
  • Bare keys can only contain A-Z, a-z, 0-9, -, and _.
  • Quote keys if they contain other characters.

Strings

Working with string values in TOML documents.

Basic Strings

Double-quoted strings with escape sequences and special characters.

Simple string values

Basic string values enclosed in double quotes.

Code
title = "Hello World"
description = "A simple configuration file"
path = "C:\\Users\\Alice\\Documents"
Execution
Terminal window
toml-parser strings.toml
Output
Terminal window
title: "Hello World"
description: "A simple configuration file"
path: "C:\\Users\\Alice\\Documents"
  • Strings are enclosed in double quotes.
  • Backslashes can be included by escaping them.

Escaped characters

Various escape sequences used in TOML strings.

Code
# Common escape sequences
tab = "Column1\tColumn2"
newline = "Line1\nLine2"
quote = "She said \"Hello!\""
backslash = "C:\\path\\to\\file"
unicode = "Café: \u00e9"
Execution
Terminal window
toml-parser escaped.toml
Output
Terminal window
tab: "Column1 Column2"
newline: "Line1\nLine2"
quote: "She said \"Hello!\""
backslash: "C:\path\to\file"
unicode: "Café: é"
  • Use \t for tabs, \n for newlines, \" for quotes.
  • Use \u for 4-digit Unicode escapes, \U for 8-digit.

Multiline Strings

Triple-quoted strings for multi-line content with literal or folded modes.

Multiline basic string

A basic multiline string using triple double quotes.

Code
description = """
This is a multiline
string with multiple
lines of text."""
Execution
Terminal window
toml-parser multiline.toml
Output
Terminal window
description: "This is a multiline\nstring with multiple\nlines of text."
  • Multiline strings preserve newlines.
  • The first newline after the opening quotes is trimmed.
  • Escape sequences still work in multiline strings.

Multiline literal string

Literal multiline strings preserve content exactly, no escaping needed.

Code
path = '''
C:\Users\Alice
C:\Users\Bob
'''
Execution
Terminal window
toml-parser literal.toml
Output
Terminal window
path: "C:\Users\Alice\nC:\Users\Bob"
  • Literal strings use triple single quotes.
  • No escape sequences are processed in literal strings.
  • Useful for paths, JSON, or other literal content.

Line folding in multiline strings

Using backslash to fold long lines without adding newlines.

Code
text = """
This is a long line \
that continues \
on the next line."""
Execution
Terminal window
toml-parser fold.toml
Output
Terminal window
text: "This is a long line that continues on the next line."
  • A backslash at the end of a line continues to the next without adding a newline.
  • This helps keep long strings readable.

String Escape Sequences

All available escape sequences in TOML strings.

Common escape sequences

Standard escape sequences for control and special characters.

Code
backspace = "Back\bspace"
tab = "Tab\there"
linefeed = "Line\nfeed"
form_feed = "Form\ffeed"
carriage_return = "Return\rhere"
quote = "Quote: \"Hello\""
backslash = "Backslash: \\"
Execution
Terminal window
toml-parser escapes.toml
Output
Terminal window
backspace: "Back\bspace"
tab: "Tab here"
linefeed: "Line\nfeed"
form_feed: "Form\ffeed"
carriage_return: "Return\rhere"
quote: "Quote: \"Hello\""
backslash: "Backslash: \"
  • \b = backspace (U+0008)
  • \t = tab (U+0009)
  • \n = line feed (U+000A)
  • \f = form feed (U+000C)
  • \r = carriage return (U+000D)
  • \" = quotation mark (U+0022)
  • \\ = backslash (U+005C)

Unicode escape sequences

Unicode escapes for 4-digit and 8-digit code points.

Code
# 4-digit Unicode escape
emoji = "Smile: \u263A"
# 8-digit Unicode escape
complex = "Mathematical: \U0001D400"
# Mix with characters
text = "Greek: \u03B1\u03B2\u03B3"
Execution
Terminal window
toml-parser unicode.toml
Output
Terminal window
emoji: "Smile: ☺"
complex: "Mathematical: 𝐀"
text: "Greek: αβγ"
  • \uXXXX for 4-digit Unicode escapes (U+0000 to U+FFFF)
  • \UXXXXXXXX for 8-digit Unicode escapes (U+00000000 to U+7FFFFFFF)
  • Use for emoji and special characters not easily typed.

Tables and Nesting

Defining and organizing tables in TOML documents.

Basic Tables

Simple table headers, dot-separated keys, and subtables.

Simple table definition

Defines two tables with their respective key-value pairs.

Code
[owner]
name = "Alice"
email = "alice@example.com"
[database]
host = "localhost"
port = 5432
Execution
Terminal window
toml-parser tables.toml
Output
Terminal window
owner:
name: "Alice"
email: "alice@example.com"
database:
host: "localhost"
port: 5432
  • Tables are headers enclosed in brackets [table_name].
  • Keys after a table belong to that table.
  • Whitespace in table names is allowed only in quoted names.

Nested tables with dot notation

Shows both dot notation and explicit table headers for nesting.

Code
# Using dot notation for subtables
database.connection.host = "localhost"
database.connection.port = 5432
database.connection.ssl = true
[database.credentials]
user = "admin"
password = "secret"
Execution
Terminal window
toml-parser nested.toml
Output
Terminal window
database:
connection:
host: "localhost"
port: 5432
ssl: true
credentials:
user: "admin"
password: "secret"
  • Dotted keys create nested tables automatically.
  • Can mix dotted keys with explicit table headers.
  • Parent tables are created automatically if needed.

Nested subtables

Hierarchical nesting of tables using bracket notation.

Code
[server]
host = "0.0.0.0"
port = 8080
[server.ssl]
enabled = true
cert = "/path/to/cert"
[server.ssl.options]
min_version = "TLSv1.2"
Execution
Terminal window
toml-parser subtables.toml
Output
Terminal window
server:
host: "0.0.0.0"
port: 8080
ssl:
enabled: true
cert: "/path/to/cert"
options:
min_version: "TLSv1.2"
  • [parent.child] defines subtables of parent.
  • Each table must be defined only once (no redefinition).

Array of Tables

Using [[array.of.tables]] syntax for multiple table items.

Simple array of tables

Creates an array of table elements with multiple items.

Code
[[products]]
id = 1
name = "Widget"
price = 9.99
[[products]]
id = 2
name = "Gadget"
price = 19.99
Execution
Terminal window
toml-parser array_tables.toml
Output
Terminal window
products:
- id: 1
name: "Widget"
price: 9.99
- id: 2
name: "Gadget"
price: 19.99
  • [[table_name]] appends a new table to an array.
  • Each [[table_name]] block creates a new element.
  • All elements have the same structure.

Nested array of tables

Array of tables nested within a parent table.

Code
[package]
name = "my-package"
[[package.dependencies]]
name = "requests"
version = "2.28.0"
[[package.dependencies]]
name = "flask"
version = "2.0.0"
Execution
Terminal window
toml-parser nested_array.toml
Output
Terminal window
package:
name: "my-package"
dependencies:
- name: "requests"
version: "2.28.0"
- name: "flask"
version: "2.0.0"
  • [[parent.child]] creates an array within the parent table.
  • Each child table is a separate element in the array.

Multiple arrays of tables

Multiple independent arrays of tables in the same document.

Code
[[users]]
name = "Alice"
role = "admin"
[[users]]
name = "Bob"
role = "user"
[[projects]]
title = "Project A"
owner = "Alice"
[[projects]]
title = "Project B"
owner = "Bob"
Execution
Terminal window
toml-parser multiple_arrays.toml
Output
Terminal window
users:
- name: "Alice"
role: "admin"
- name: "Bob"
role: "user"
projects:
- title: "Project A"
owner: "Alice"
- title: "Project B"
owner: "Bob"
  • Each [[name]] creates a separate array.
  • Arrays can be defined independently.

Nested Structures

Complex deeply nested tables and hierarchical data.

Deeply nested tables

Demonstrates multiple levels of nesting with different branches.

Code
[server.http.handlers.api]
endpoint = "/api/v1"
timeout = 30
[server.http.handlers.websocket]
endpoint = "/ws"
timeout = 0
[server.https.ssl]
cert = "/path/to/cert"
key = "/path/to/key"
Execution
Terminal window
toml-parser deep_nesting.toml
Output
Terminal window
server:
http:
handlers:
api:
endpoint: "/api/v1"
timeout: 30
websocket:
endpoint: "/ws"
timeout: 0
https:
ssl:
cert: "/path/to/cert"
key: "/path/to/key"
  • TOML supports unlimited nesting depth.
  • Use clear naming to avoid confusion in deeply nested structures.
  • Dotted keys can simplify defining deeply nested values.

Complex hierarchical structure

Combines tables, arrays of tables, and nested structures.

Code
[app]
name = "MyApp"
version = "1.0.0"
[app.features]
auth = true
api = true
websocket = false
[[app.features.modules]]
name = "Auth"
enabled = true
[[app.features.modules]]
name = "API"
enabled = true
[app.logging]
level = "info"
format = "json"
Execution
Terminal window
toml-parser complex_nested.toml
Output
Terminal window
app:
name: "MyApp"
version: "1.0.0"
features:
auth: true
api: true
websocket: false
modules:
- name: "Auth"
enabled: true
- name: "API"
enabled: true
logging:
level: "info"
format: "json"
  • Mix different structure types for flexibility.
  • Organize by functionality or domain.

Data Types

Detailed coverage of TOML data types and representations.

Numbers

Integers, floats, scientific notation, and underscores in numbers.

Integer number formats

TOML supports decimal, hexadecimal, octal, and binary integers.

Code
# Decimal integers
count = 42
negative = -17
# Hexadecimal (0x prefix)
hex_value = 0xDEADBEEF
# Octal (0o prefix)
octal = 0o755
# Binary (0b prefix)
binary = 0b11010110
Execution
Terminal window
toml-parser integers.toml
Output
Terminal window
count: 42
negative: -17
hex_value: 3735928559
octal: 493
binary: 214
  • Integers are 64-bit signed numbers.
  • Leading zeros are not allowed in decimal notation.
  • Hex, octal, and binary integers have specific prefixes.

Float number formats

TOML supports standard floats, scientific notation, and special values.

Code
# Standard float
pi = 3.14159
# Negative float
temperature = -40.0
# Scientific notation
large = 5e+22
small = 1.47e-12
# Special float values
infinity = inf
neg_infinity = -inf
not_number = nan
Execution
Terminal window
toml-parser floats.toml
Output
Terminal window
pi: 3.14159
temperature: -40.0
large: 5e+22
small: 1.47e-12
infinity: Infinity
neg_infinity: -Infinity
not_number: NaN
  • Floats are 64-bit (IEEE 754 double precision).
  • Scientific notation uses 'e' or 'E'.
  • Special values inf, -inf, nan represent infinity and NaN.

Numbers with underscores

Underscores improve readability of large numbers.

Code
# Readable large numbers
million = 1_000_000
phone = 555_123_4567
binary = 0b1010_1010
# Floats with underscores
pi = 3.14_159_265
scientific = 1.602_176_634e-19
Execution
Terminal window
toml-parser underscores.toml
Output
Terminal window
million: 1000000
phone: 5551234567
binary: 170
pi: 3.14159265
scientific: 1.602176634e-19
  • Underscores can be placed between digits for readability.
  • Leading/trailing underscores are not allowed.
  • Underscores are ignored during parsing.

Booleans and Null

Boolean true/false values and null representation in TOML.

Boolean values

TOML uses lowercase true and false for boolean values.

Code
# Boolean values are lowercase
enabled = true
debug = false
[features]
auth = true
logging = false
updates = true
Execution
Terminal window
toml-parser booleans.toml
Output
Terminal window
enabled: true
debug: false
features:
auth: true
logging: false
updates: true
  • Boolean values are lowercase (true, false).
  • No yes/no or on/off alternatives in TOML.
  • Booleans are distinct from strings.

Representing null or absence

TOML doesn't have a null type; use conventions or omit keys.

Code
# TOML doesn't have a native null type
# Options for representing absence:
# 1. Omit the key entirely
# optional_field = (not present)
# 2. Use empty string
empty = ""
# 3. Use special marker values
null_marker = "null"
unset = "unset"
none = "none"
Execution
Terminal window
toml-parser null.toml
Output
Terminal window
empty: ""
null_marker: "null"
unset: "unset"
none: "none"
  • TOML does not have a native null or None value.
  • Omit the key entirely to represent absence.
  • Use empty string or special marker strings if needed.

Dates and Times

ISO 8601 formatted dates, times, and datetimes with timezone support.

Date and time formats

Basic date, time, and local datetime formats in ISO 8601.

Code
# Date (RFC 3339 profile of ISO 8601)
birthday = 1990-05-27
# Time (no date)
alarm = 15:30:00
# Local DateTime (date and time, no timezone)
meeting = 2021-12-25T10:30:00
Execution
Terminal window
toml-parser dates.toml
Output
Terminal window
birthday: 1990-05-27
alarm: 15:30:00
meeting: 2021-12-25T10:30:00
  • Dates follow YYYY-MM-DD format.
  • Times follow HH:MM:SS or HH:MM:SS.ffffff format.
  • LocalDateTime combines date and time without timezone.

Datetime with timezone

Datetime values with timezone information and fractional seconds.

Code
# UTC timezone (Z suffix)
created = 2021-12-25T10:30:00Z
# With offset
eastern = 2021-12-25T10:30:00-05:00
# With positive offset
tokyo = 2021-12-25T10:30:00+09:00
# Milliseconds precision
precise = 2021-12-25T10:30:00.123Z
Execution
Terminal window
toml-parser datetimes.toml
Output
Terminal window
created: 2021-12-25T10:30:00Z
eastern: 2021-12-25T10:30:00-05:00
tokyo: 2021-12-25T10:30:00+09:00
precise: 2021-12-25T10:30:00.123Z
  • Z suffix indicates UTC (Zulu) time.
  • Offset format is ±HH:MM.
  • Fractional seconds support up to nanosecond precision.

Advanced Features

Advanced TOML features for complex configurations.

Inline Tables

Compact single-line table syntax with {key = value} format.

Simple inline table

Inline tables provide a compact way to define tables on a single line.

Code
point = { x = 1, y = 2 }
color = { r = 255, g = 128, b = 0 }
person = { name = "Alice", age = 30 }
Execution
Terminal window
toml-parser inline.toml
Output
Terminal window
point:
x: 1
y: 2
color:
r: 255
g: 128
b: 0
person:
name: "Alice"
age: 30
  • Inline tables are enclosed in curly braces.
  • Keys and values are separated by equals with optional spaces.
  • Inline tables cannot span multiple lines.

Nested inline tables

Inline tables can be nested and used in arrays.

Code
# Inline table containing inline table
config = {
database = { host = "localhost", port = 5432 },
cache = { host = "redis", ttl = 3600 }
}
# Array of inline tables
points = [
{ x = 0, y = 0 },
{ x = 1, y = 2 },
{ x = 3, y = 4 }
]
Execution
Terminal window
toml-parser nested_inline.toml
Output
Terminal window
config:
database:
host: "localhost"
port: 5432
cache:
host: "redis"
ttl: 3600
points:
- x: 0
y: 0
- x: 1
y: 2
- x: 3
y: 4
  • Inline tables cannot be redefined or extended later.
  • Useful for simple, fixed data structures.

Advanced DateTime

Offset datetimes, local datetimes, and time precision handling.

All datetime variants

Examples of all TOML datetime type variants.

Code
# Offset DateTime (with timezone)
utc_time = 2021-12-25T10:30:00Z
eastern_time = 2021-12-25T10:30:00-05:00
# Local DateTime (no timezone)
local_meeting = 2021-12-25T10:30:00
# Local Date (no time)
deadline = 2021-12-31
# Local Time (no date)
opening_time = 09:00:00
Execution
Terminal window
toml-parser all_datetime.toml
Output
Terminal window
utc_time: 2021-12-25T10:30:00Z
eastern_time: 2021-12-25T10:30:00-05:00
local_meeting: 2021-12-25T10:30:00
deadline: 2021-12-31
opening_time: 09:00:00
  • Offset DateTime includes timezone information.
  • Local DateTime is timezone-naive.
  • Local Date and Local Time can exist independently.

Fractional seconds and precision

Demonstrates various precision levels in fractional seconds.

Code
# Milliseconds
ms_precision = 2021-12-25T10:30:00.123Z
# Microseconds
us_precision = 2021-12-25T10:30:00.123456Z
# Nanoseconds
ns_precision = 2021-12-25T10:30:00.123456789Z
# Trailing zeros
long_precision = 2021-12-25T10:30:00.1Z
Execution
Terminal window
toml-parser precision.toml
Output
Terminal window
ms_precision: 2021-12-25T10:30:00.123Z
us_precision: 2021-12-25T10:30:00.123456Z
ns_precision: 2021-12-25T10:30:00.123456789Z
long_precision: 2021-12-25T10:30:00.1Z
  • Fractional seconds are optional and can be 1-9 digits.
  • No precision loss; values are preserved as specified.

Comments and Formatting

Effective commenting and formatting practices in TOML.

Effective commenting

Shows effective use of comments for documentation.

Code
# Main application configuration
# Last updated: 2025-02-28
title = "MyApp" # Application title
version = "1.0.0"
# Database connection settings
[database]
host = "localhost" # Database server hostname
port = 5432 # Standard PostgreSQL port
ssl = true # Enable SSL for secure connections
Execution
Terminal window
toml-parser commented.toml
Output
Terminal window
title: "MyApp"
version: "1.0.0"
database:
host: "localhost"
port: 5432
ssl: true
  • Comments start with
  • Inline comments are allowed after values.
  • Comments help clarify non-obvious configuration.

Organized file structure

Well-organized file structure with clear section headers.

Code
# ============================================================================
# Application Configuration
# ============================================================================
[metadata]
name = "MyApp"
version = "1.0.0"
author = "Team"
# ============================================================================
# Server Configuration
# ============================================================================
[server]
host = "0.0.0.0"
port = 8080
[server.ssl]
enabled = true
cert = "/path/to/cert"
# ============================================================================
# Database Configuration
# ============================================================================
[database]
url = "postgresql://localhost/mydb"
Execution
Terminal window
toml-parser organized.toml
Output
Terminal window
metadata:
name: "MyApp"
version: "1.0.0"
author: "Team"
server:
host: "0.0.0.0"
port: 8080
ssl:
enabled: true
cert: "/path/to/cert"
database:
url: "postgresql://localhost/mydb"
  • Use visual separators (comment lines) for clarity.
  • Group related configurations into sections.
  • Maintain consistent formatting throughout the file.

Best Practices

Best practices for writing effective TOML configurations.

Common Patterns

Patterns used in real-world TOML files and package manifests.

Cargo.toml (Rust) style

Standard structure of Cargo.toml for Rust projects.

Code
[package]
name = "my-app"
version = "0.1.0"
edition = "2021"
description = "My awesome application"
authors = ["Me <me@example.com>"]
[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
[dev-dependencies]
pytest = "0.13"
[profile.release]
opt-level = 3
Execution
Terminal window
cargo build
  • [package] section contains metadata.
  • [dependencies] lists production dependencies.
  • [dev-dependencies] for testing dependencies.
  • Feature specifications are common.

pyproject.toml (Python) style

Standard structure of pyproject.toml for Python projects.

Code
[project]
name = "my-package"
version = "0.1.0"
description = "A Python package"
authors = [{name = "Alice", email = "alice@example.com"}]
requires-python = ">=3.8"
[project.dependencies]
requests = ">=2.0"
flask = ">=2.0"
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
Execution
Terminal window
pip install .
  • [project] contains package metadata.
  • Author details use inline table format.
  • [build-system] specifies build requirements.

Application config file pattern

Typical application configuration file structure.

Code
# [app.toml] - Server configuration
[app]
name = "MyService"
environment = "production"
debug = false
[server]
host = "0.0.0.0"
port = 8080
workers = 4
[database]
url = "postgresql://user:pass@localhost/db"
pool_size = 20
[logging]
level = "info"
format = "json"
file = "/var/log/myservice.log"
[[services]]
name = "auth"
url = "http://auth-service:8000"
[[services]]
name = "cache"
url = "redis://localhost:6379"
Execution
Terminal window
myapp --config app.toml
  • Metadata in [app] section.
  • Server/database settings in dedicated sections.
  • External services in array of tables.

Readability and Style

Organizing keys and maintaining consistent formatting.

Well-organized TOML file

Configuration organized for clarity and maintainability.

Code
# Services Configuration
# Well-organized with logical grouping
[metadata]
version = "1.0.0"
updated = 2025-02-28
[api]
# Core API settings
host = "0.0.0.0"
port = 8000
timeout = 30
[api.auth]
# Authentication configuration
enabled = true
jwt_secret = "your-secret-key"
token_expire_hours = 24
[api.cors]
# CORS settings
allowed_origins = ["http://localhost:3000"]
allowed_methods = ["GET", "POST", "PUT"]
[database]
host = "localhost"
port = 5432
name = "myapp"
pool_size = 20
[logging]
level = "info"
format = "json"
Execution
Terminal window
app --config config.toml
  • Use descriptive section names.
  • Add comments explaining purpose of sections.
  • Keep related items grouped together.
  • Use consistent indentation (though not required).

Naming conventions

Demonstrates consistent naming conventions.

Code
# ✓ Good naming conventions
[database]
connection_timeout = 10
max_pool_size = 20
retry_attempts = 3
[cache]
redis_host = "localhost"
redis_port = 6379
ttl_seconds = 3600
[service]
api_key = "secret"
api_version = "v1"
api_timeout = 30
Execution
Terminal window
app --validate-config
Output
Terminal window
Configuration is valid
  • Use snake_case for key names.
  • Use descriptive suffixes (_host, _port, _timeout, etc.).
  • Keep names consistent across similar settings.
  • Avoid ambiguous abbreviations.

Validation and Usage

Loading and parsing TOML files in programming languages.

Python - Loading TOML with tomllib

Python example using the built-in tomllib module (Python 3.11+).

Code
[app]
name = "MyApp"
debug = false
[database]
url = "postgresql://localhost/myapp"
pool_size = 20
Execution
import tomllib
with open('config.toml', 'rb') as f:
config = tomllib.load(f)
print(config['app']['name'])
print(config['database']['pool_size'])
Output
Terminal window
MyApp
20
  • tomllib requires opened file in binary mode ('rb').
  • For older Python, use the 'tomli' package.
  • Returns a dictionary with nested structure.

Rust - Loading TOML with toml crate

Rust uses the toml crate to parse TOML files.

Code
[server]
host = "0.0.0.0"
port = 8080
[server.ssl]
cert = "/path/to/cert.pem"
key = "/path/to/key.pem"
Execution
Terminal window
cargo run
Output
Terminal window
Server listening on 0.0.0.0:8080
  • Rust has strong typing for TOML values.
  • Use serde for deserializing into structs.
  • Includes validation through type checking.

TOML validation and schema

Validation ensures TOML matches expected structure.

Code
# Configuration that should be validated
[app]
name = "Service"
# Required fields: app.name, server.port
# Optional fields: debug, logging.level
[server]
port = 8080
# host must be an IP or hostname
host = "0.0.0.0"
[logging]
level = "info" # must be: debug, info, warn, error
Execution
Terminal window
validate-toml --schema config.schema.json config.toml
Output
Terminal window
Configuration is valid
  • JSON Schema can define TOML structure.
  • Type checking during deserialization.
  • Document required vs optional fields.