API Reference

This page contains the auto-generated API documentation for fabricpy.

Main Package

fabricpy - A lightweight helper library for writing Fabric mods in Python.

fabricpy provides a simple, Pythonic interface for creating Minecraft Fabric mods without needing to write Java directly. It handles mod configuration, item and block registration, recipe creation, and project compilation.

This module exposes all the main classes and utilities needed to create Fabric mods:

  • ModConfig: Main configuration and compilation class

  • Item/FoodItem: Item registration classes

  • Block: Block registration class

  • ItemGroup: Custom creative tab creation

  • RecipeJson: Recipe definition helper

  • LootTable/LootPool: Loot table definition and builder classes

  • item_group: Vanilla creative tab constants

Example

Basic mod creation:

import fabricpy

# Create mod configuration
mymod = fabricpy.ModConfig(
    mod_id="mymod",
    name="My Mod",
    version="1.0.0",
    description="A simple example mod",
    authors=["Your Name"]
)

# Create and register an item
item = fabricpy.Item(
    id="mymod:example_item",
    name="Example Item"
)
mymod.registerItem(item)

# Compile and run
mymod.compile()
mymod.run()
__all__

List of public API symbols exported by this module.

Type:

list

class ModConfig(mod_id, name, description, version, authors, project_dir='my-fabric-mod', template_repo='https://github.com/FabricMC/fabric-example-mod.git', enable_testing=True, generate_unit_tests=True, generate_game_tests=False)[source]

Bases: object

Main configuration class for generating Fabric mod projects.

This class handles the entire process of creating a Minecraft Fabric mod from Python definitions. It manages mod metadata, item/block registration, Java code generation, texture processing, and project compilation.

The class supports: - Cloning and configuring the Fabric example-mod template - Registering items, food items, and blocks with custom properties - Generating Java source files for all registered components - Processing textures and generating model/blockstate JSON files - Creating recipe JSON files from RecipeJson objects - Setting up Fabric testing framework with unit and game tests - Building and running the mod in development mode

mod_id

Unique identifier for the mod.

Type:

str

name

Display name of the mod.

Type:

str

description

Description of what the mod does.

Type:

str

version

Version string for the mod.

Type:

str

authors

List of mod authors.

Type:

List[str]

project_dir

Directory where the mod project will be generated.

Type:

str

template_repo

Git repository URL for the Fabric template.

Type:

str

enable_testing

Whether to set up Fabric testing framework.

Type:

bool

generate_unit_tests

Whether to generate unit tests.

Type:

bool

generate_game_tests

Whether to generate game tests.

Type:

bool

registered_items

List of registered Item and FoodItem objects.

Type:

List

registered_blocks

List of registered Block objects.

Type:

List

Example

Basic mod setup:

mod = ModConfig(
    mod_id="mymod",
    name="My Awesome Mod",
    version="1.0.0",
    description="Adds cool items to Minecraft",
    authors=["Your Name"]
)

# Register an item
item = Item(id="mymod:cool_item", name="Cool Item")
mod.registerItem(item)

# Compile and run
mod.compile()
mod.run()
__init__(mod_id, name, description, version, authors, project_dir='my-fabric-mod', template_repo='https://github.com/FabricMC/fabric-example-mod.git', enable_testing=True, generate_unit_tests=True, generate_game_tests=False)[source]

Initialize a new ModConfig instance.

Parameters:
  • mod_id (str) – Unique identifier for the mod. Must be valid for Minecraft namespaces (lowercase, no spaces, alphanumeric + underscore/hyphen).

  • name (str) – Human-readable display name for the mod.

  • description (str) – Brief description of what the mod does.

  • version (str) – Version string for the mod (e.g., “1.0.0”).

  • authors (List[str] | tuple[str, ]) – List or tuple of author names.

  • project_dir (str, optional) – Directory name for the generated mod project. Defaults to “my-fabric-mod”.

  • template_repo (str, optional) – Git repository URL for the Fabric template. Defaults to the official Fabric example-mod repository.

  • enable_testing (bool, optional) – Whether to set up Fabric testing framework. Defaults to True.

  • generate_unit_tests (bool, optional) – Whether to generate unit tests for registered items and blocks. Defaults to True.

  • generate_game_tests (bool, optional) – Whether to generate Fabric game tests that run in a Minecraft environment. Defaults to False to prevent build compilation issues.

Example

Creating a mod configuration:

config = ModConfig(
    mod_id="awesome_mod",
    name="Awesome Mod",
    description="Makes Minecraft more awesome",
    version="1.2.3",
    authors=["Alice", "Bob"],
    project_dir="my-awesome-mod"
)
registerItem(item)[source]

Register an Item instance with this mod.

Parameters:

item (Item) – The Item instance to register. This can be a basic Item or any subclass such as FoodItem.

Example

Registering a basic item:

item = Item(id="mymod:stone_sword", name="Stone Sword")
mod.registerItem(item)
registerFoodItem(food_item)[source]

Register a FoodItem instance with this mod.

Parameters:

food_item (FoodItem) – The FoodItem instance to register. This is a convenience method that’s equivalent to registerItem() for food items.

Example

Registering a food item:

apple = FoodItem(
    id="mymod:golden_apple",
    name="Golden Apple",
    nutrition=6,
    saturation=0.8
)
mod.registerFoodItem(apple)
registerBlock(block)[source]

Register a Block instance with this mod.

Parameters:

block (Block) – The Block instance to register. This will generate both the block itself and its corresponding BlockItem.

Example

Registering a block:

block = Block(
    id="mymod:diamond_block",
    name="Diamond Block",
    block_texture_path="textures/diamond_block.png"
)
mod.registerBlock(block)
registerLootTable(name, loot_table)[source]

Register a standalone loot table (entity / chest / custom).

Block loot tables should be attached directly to the Block via its loot_table attribute. Use this method for loot tables that are not tied to a specific block, such as entity drops, chest loot, or gameplay loot tables.

Parameters:
  • name (str) – Filename stem for the loot table (e.g. "zombie"). The file will be written to data/<mod_id>/loot_table/<category>/<name>.json.

  • loot_table – A LootTable instance.

Example

Registering an entity loot table:

from fabricpy import LootTable, LootPool

lt = LootTable.entity([
    LootPool().rolls(1).entry("mymod:fang")
])
mod.registerLootTable("custom_zombie", lt)
compile()[source]

Compile the mod project from registered components.

This is the main method that orchestrates the entire mod generation process: 1. Clones the Fabric example-mod template repository 2. Updates fabric.mod.json with mod metadata 3. Generates Java source files for items and item groups 4. Generates Java source files for blocks (if any) 5. Copies textures and generates model/blockstate JSON files 6. Writes recipe JSON files for items/blocks with recipes 7. Updates language files with item/block/group translations 8. Sets up Fabric testing framework (if enabled) 9. Generates unit and game tests (if enabled)

The generated project will be a complete, buildable Fabric mod.

Raises:

Example

Compiling a mod:

mod.registerItem(Item(id="mymod:test", name="Test"))
mod.compile()  # Creates complete mod project

Note

This method must be called before build() or run().

clone_repository(repo_url, dst)[source]

Clone a Git repository to the specified destination.

Parameters:
  • repo_url (str) – The URL of the Git repository to clone.

  • dst (str) – The destination directory path where the repository will be cloned.

Raises:

subprocess.CalledProcessError – If the git clone command fails.

Example

Cloning the Fabric example mod template:

mod.clone_repository(
    "https://github.com/FabricMC/fabric-example-mod.git",
    "/path/to/my-mod"
)
update_mod_metadata(path, data)[source]

Update the fabric.mod.json file with mod metadata.

Parameters:
  • path (str) – Path to the fabric.mod.json file to update.

  • data (dict) – Dictionary containing the metadata to update. Common keys include: - id: Mod identifier - name: Mod display name - version: Mod version string - description: Mod description - authors: List of author names

Raises:

Example

Updating mod metadata:

mod.update_mod_metadata(
    "src/main/resources/fabric.mod.json",
    {
        "id": "mymod",
        "name": "My Awesome Mod",
        "version": "1.0.0",
        "description": "An awesome Minecraft mod",
        "authors": ["Author Name"]
    }
)
write_recipe_files(project_dir, mod_id)[source]

Write recipe JSON files for items and blocks that have recipes.

Scans all registered items and blocks for attached RecipeJson objects and writes them as JSON files in the mod’s data/recipes directory. Each recipe file is named based on the result item ID.

Parameters:
  • project_dir (str) – Root directory of the mod project.

  • mod_id (str) – The mod’s identifier, used in the data directory path.

Note

  • Only items and blocks with non-None recipe attributes are processed

  • Recipe files are written to data/{mod_id}/recipe/

  • File names are derived from the recipe’s result_id or the item/block ID

  • Existing recipe files will be overwritten

Example

Writing recipes after registering items with recipes:

# Item with recipe
item = Item(
    id="mymod:diamond_sword",
    name="Diamond Sword",
    recipe=RecipeJson({...})
)
mod.registerItem(item)

# This will create the recipe file
mod.write_recipe_files(project_dir, "mymod")
write_loot_table_files(project_dir, mod_id)[source]

Write loot-table JSON files for blocks and standalone registrations.

Scans all registered blocks for attached loot_table attributes and all entries added via registerLootTable(), then writes them as JSON files under data/<mod_id>/loot_table/<category>/.

For blocks the filename is derived from the block ID. For standalone tables the filename is the name passed to registerLootTable().

Parameters:
  • project_dir (str) – Root directory of the mod project.

  • mod_id (str) – The mod’s identifier, used in the data directory path.

Note

This method is called automatically during compile().

Example

Writing loot tables manually (usually not needed):

mod.write_loot_table_files("my-mod-project", "mymod")
write_block_tags(project_dir, mod_id)[source]

Write mineable and mining-level block-tag JSON files.

For every registered block that specifies a tool_type (and/or keys in mining_speeds), the block is added to the corresponding data/minecraft/tags/block/mineable/<tool>.json tags.

Blocks that specify a mining_level ("stone", "iron", or "diamond") are also added to data/minecraft/tags/block/needs_<level>_tool.json.

Parameters:
  • project_dir (str) – Root directory of the mod project.

  • mod_id (str) – The mod’s identifier.

create_item_files(project_dir, package_path)[source]

Generate Java source files for item registration and management.

Creates TutorialItems.java and CustomItem.java files in the specified package. TutorialItems contains registration code for all items, while CustomItem provides a base class for custom item behavior.

Parameters:
  • project_dir (str) – Root directory of the mod project.

  • package_path (str) – Java package path for the generated files (e.g., “com.example.mymod.items”).

Note

Generated files include: - TutorialItems.java: Static registration for all mod items - CustomItem.java: Base class for items with custom behavior

Example

Creating item files:

mod.create_item_files(
    "/path/to/mod",
    "com.example.mymod.items"
)
create_item_group_files(project_dir, package_path)[source]

Generate Java source files for custom item groups (creative tabs).

Creates the TutorialItemGroups.java file containing Java code for all custom ItemGroup objects. This handles creative tab registration, icon assignment, and adding items/blocks to the custom tabs.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • package_path (str) – The Java package path for the item group classes (e.g., “com.example.mymod.items”).

Note

This method is called automatically during compile() when custom ItemGroup objects are detected. If no custom groups exist, no files are generated.

update_mod_initializer(project_dir, pkg)[source]

Add item initialization code to the mod’s main initializer.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • pkg (str) – The Java package name containing the TutorialItems class.

update_mod_initializer_itemgroups(project_dir, pkg)[source]

Add item group initialization code to the mod’s main initializer.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • pkg (str) – The Java package name containing the TutorialItemGroups class.

update_mod_initializer_blocks(project_dir, pkg)[source]

Add block initialization code to the mod’s main initializer.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • pkg (str) – The Java package name containing the TutorialBlocks class.

copy_texture_and_generate_models(project_dir, mod_id)[source]

Copy item textures and generate model/item definition JSON files.

Processes all registered items by copying their texture files to the mod’s assets directory and generating the corresponding model and item definition JSON files required by Minecraft’s resource pack system.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • mod_id (str) – The mod’s identifier, used for asset paths.

Note

For each item, this method: - Copies the texture PNG file to assets/<mod_id>/textures/item/ - Generates a model JSON file in assets/<mod_id>/models/item/ - Generates an item definition JSON file in assets/<mod_id>/items/ Items without valid texture paths are skipped with a warning.

update_item_lang_file(project_dir, mod_id)[source]

Update the English language file with item translations.

Adds or updates translation entries for all registered items in the mod’s en_us.json language file.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • mod_id (str) – The mod’s identifier for namespacing translations.

update_item_group_lang_entries(project_dir, mod_id)[source]

Update the English language file with item group translations.

Adds translation entries for all custom item groups defined in the mod.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • mod_id (str) – The mod’s identifier for namespacing translations.

create_block_files(project_dir, package_path)[source]

Generate Java source files for all registered blocks.

Creates the TutorialBlocks.java and CustomBlock.java files containing block registration and implementation logic.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • package_path (str) – The Java package path for the block classes.

copy_block_textures_and_generate_models(project_dir, mod_id)[source]

Copy block textures and generate model/blockstate JSON files.

Processes all registered blocks by copying their texture files and generating the corresponding model, blockstate, and item definition JSON files required by Minecraft’s resource pack system.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • mod_id (str) – The mod’s identifier for namespacing resources.

update_block_lang_file(project_dir, mod_id)[source]

Update the English language file with block translations.

Adds or updates translation entries for all registered blocks in the mod’s en_us.json language file. Creates entries for both the block and its corresponding item form.

Parameters:
  • project_dir (str) – The root directory of the mod project.

  • mod_id (str) – The mod’s identifier for namespacing translations.

build()[source]

Build the mod JAR file using Gradle.

Requires compile() to have been called first. Enters the mod project directory and runs ./gradlew build to produce the distributable JAR file.

The built JAR will be located in the build/libs/ directory of the project.

Raises:

Example

Building the mod:

mod.compile()  # Must be called first
mod.build()    # Creates JAR in build/libs/
run()[source]

Run the mod in development mode using Fabric Loader.

Launches a Minecraft client with the mod loaded for testing and development. This uses Gradle’s runClient task which sets up a development environment.

Raises:

Example

Running the mod for testing:

mod.compile()  # Must be called first
mod.run()      # Launches Minecraft with the mod
setup_fabric_testing(project_dir)[source]

Set up Fabric testing framework in the project.

Configures the mod project to support Fabric’s testing capabilities by enhancing build.gradle with testing dependencies and configuration, and ensuring gradle.properties has the necessary testing properties.

Parameters:

project_dir (str) – The root directory of the mod project.

Note

This method is called automatically during compile() when enable_testing is True. It sets up the foundation for both unit tests and game tests but doesn’t generate the test files themselves (see generate_fabric_unit_tests and generate_fabric_game_tests).

generate_fabric_unit_tests(project_dir)[source]

Generate Fabric unit tests for the mod.

Creates comprehensive unit tests that validate item registration, recipe functionality, and mod integration. Tests are generated based on the registered items, blocks, and their properties.

Parameters:

project_dir (str) – The root directory of the mod project.

Note

Generated tests include: - Item registration verification - Food item property validation - Recipe validation and result ID checking - Complete mod integration testing Test files are placed in src/test/java/ following standard conventions.

generate_fabric_game_tests(project_dir)[source]

Generate Fabric game tests for the mod.

Creates game tests that run within a Minecraft environment to validate mod functionality in actual gameplay conditions. These tests can interact with the world, place blocks, and test item behavior.

Parameters:

project_dir (str) – The root directory of the mod project.

Note

Generated game tests include: - Server-side item and block functionality testing - Client-side interaction and rendering validation - Block placement and world interaction tests Game test files are placed in src/gametest/java/ and require a separate fabric.mod.json for the test environment.

class Item(id=None, name=None, max_stack_size=64, texture_path=None, recipe=None, item_group=None)[source]

Bases: object

Represents a custom item in a Fabric mod.

The Item class handles the definition of custom items including their properties, textures, recipes, and creative tab assignment. Items are registered with a ModConfig instance and compiled into the final mod.

Parameters:
  • id (str | None) – The registry identifier for the item (e.g., “mymod:example_item”). If None, must be set before compilation.

  • name (str | None) – The display name for the item shown in-game. If None, must be set before compilation.

  • max_stack_size (int) – Maximum number of items that can be stacked together. Defaults to 64.

  • texture_path (str | None) – Path to the item’s texture file relative to mod resources. If None, a default texture will be used.

  • recipe (object | None) – Recipe definition for crafting this item. Can be a RecipeJson instance or None for no recipe.

  • item_group (object | str | None) – Creative tab to place this item in. Can be an ItemGroup instance, a string constant from item_group module, or None.

id

The registry identifier for the item.

Type:

str

name

The display name for the item.

Type:

str

max_stack_size

Maximum stack size for the item.

Type:

int

texture_path

Path to the item’s texture file.

Type:

str

recipe

Recipe definition for crafting this item.

Type:

RecipeJson

item_group

Creative tab assignment for the item.

Type:

ItemGroup | str

Example

Creating a basic item:

item = Item(
    id="mymod:copper_sword",
    name="Copper Sword",
    max_stack_size=1,
    texture_path="textures/items/copper_sword.png",
    item_group=fabricpy.item_group.COMBAT
)

Creating an item with a recipe:

recipe = RecipeJson({
    "type": "minecraft:crafting_shaped",
    "pattern": ["#", "#", "/"],
    "key": {
        "#": "minecraft:copper_ingot",
        "/": "minecraft:stick"
    },
    "result": {"id": "mymod:copper_sword", "count": 1}
})

item = Item(
    id="mymod:copper_sword",
    name="Copper Sword",
    recipe=recipe
)
__init__(id=None, name=None, max_stack_size=64, texture_path=None, recipe=None, item_group=None)[source]

Initialize a new Item instance.

Parameters:
  • id (str | None) – The registry identifier for the item.

  • name (str | None) – The display name for the item.

  • max_stack_size (int) – Maximum number of items that can be stacked.

  • texture_path (str | None) – Path to the item’s texture file.

  • recipe (object | None) – Recipe definition for crafting this item.

  • item_group (object | str | None) – Creative tab to place this item in.

class FoodItem(id=None, name=None, max_stack_size=64, texture_path=None, nutrition=0, saturation=0.0, always_edible=False, recipe=None, item_group=None)[source]

Bases: Item

Represents a custom food item in a Fabric mod.

FoodItem extends the base Item class to add food-specific properties including nutrition value, saturation, and whether the item can always be eaten regardless of hunger level.

Parameters:
  • id (str | None) – The registry identifier for the food item (e.g., “mymod:golden_apple”). If None, must be set before compilation.

  • name (str | None) – The display name for the food item shown in-game. If None, must be set before compilation.

  • max_stack_size (int) – Maximum number of items that can be stacked together. Defaults to 64.

  • texture_path (str | None) – Path to the item’s texture file relative to mod resources. If None, a default texture will be used.

  • nutrition (int) – Number of hunger points restored when eaten (half-hearts on hunger bar). Defaults to 0.

  • saturation (float) – Saturation value provided when eaten. Higher values prevent hunger from decreasing quickly. Defaults to 0.0.

  • always_edible (bool) – Whether the food can be eaten even when the player’s hunger bar is full. Defaults to False.

  • recipe (object | None) – Recipe definition for crafting this food item. Can be a RecipeJson instance or None for no recipe.

  • item_group (object | str | None) – Creative tab to place this item in. Can be an ItemGroup instance, a string constant from item_group module, or None. Typically FOOD_AND_DRINK for food items.

nutrition

Hunger points restored when eaten.

Type:

int

saturation

Saturation value provided when eaten.

Type:

float

always_edible

Whether the food can always be eaten.

Type:

bool

Example

Creating a basic food item:

apple = FoodItem(
    id="mymod:golden_apple",
    name="Golden Apple",
    nutrition=4,
    saturation=9.6,
    always_edible=True,
    item_group=fabricpy.item_group.FOOD_AND_DRINK
)

Creating a food item with a recipe:

recipe = RecipeJson({
    "type": "minecraft:crafting_shaped",
    "pattern": ["###", "#A#", "###"],
    "key": {
        "#": "minecraft:gold_ingot",
        "A": "minecraft:apple"
    },
    "result": {"id": "mymod:golden_apple", "count": 1}
})

apple = FoodItem(
    id="mymod:golden_apple",
    name="Golden Apple",
    nutrition=4,
    saturation=9.6,
    recipe=recipe
)
__init__(id=None, name=None, max_stack_size=64, texture_path=None, nutrition=0, saturation=0.0, always_edible=False, recipe=None, item_group=None)[source]

Initialize a new FoodItem instance.

Parameters:
  • id (str | None) – The registry identifier for the food item.

  • name (str | None) – The display name for the food item.

  • max_stack_size (int) – Maximum number of items that can be stacked.

  • texture_path (str | None) – Path to the item’s texture file.

  • nutrition (int) – Number of hunger points restored when eaten.

  • saturation (float) – Saturation value provided when eaten.

  • always_edible (bool) – Whether the food can be eaten when hunger is full.

  • recipe (object | None) – Recipe definition for crafting this food item.

  • item_group (object | str | None) – Creative tab to place this item in.

class ToolItem(id=None, name=None, max_stack_size=1, texture_path=None, durability=0, mining_speed_multiplier=1.0, attack_damage=1.0, mining_level=0, enchantability=0, repair_ingredient=None, recipe=None, item_group=None)[source]

Bases: Item

Represents a tool item in a Fabric mod.

ToolItem extends the base Item class to add properties relevant to tools and weapons, including durability, mining speed, attack damage, mining level, enchantability and a repair ingredient.

Parameters:
  • id (str | None) – The registry identifier for the tool item (e.g., "mymod:obsidian_pickaxe"). If None, must be set before compilation.

  • name (str | None) – The display name for the tool item shown in-game. If None, must be set before compilation.

  • max_stack_size (int) – Maximum number of items that can be stacked together. Defaults to 1 for tools.

  • texture_path (str | None) – Path to the item’s texture file relative to mod resources. If None, a default texture will be used.

  • durability (int) – Number of uses before the tool breaks. Defaults to 0.

  • mining_speed_multiplier (float) – Speed multiplier when mining blocks. Defaults to 1.0.

  • attack_damage (float) – Damage dealt when used as a weapon. Defaults to 1.0.

  • mining_level (int) – Mining level of the tool. Defaults to 0.

  • enchantability (int) – How easily the tool can receive enchantments. Defaults to 0.

  • repair_ingredient (str | None) – Item ID used to repair the tool. Defaults to None.

  • recipe (object | None) – Recipe definition for crafting this tool item. Can be a RecipeJson instance or None for no recipe.

  • item_group (object | str | None) – Creative tab to place this item in. Can be an ItemGroup instance, a string constant from fabricpy.item_group, or None.

durability

Number of uses before the tool breaks.

Type:

int

mining_speed_multiplier

Speed multiplier when mining blocks.

Type:

float

attack_damage

Damage dealt when used as a weapon.

Type:

float

mining_level

Mining tier of the tool (e.g., 0 for wooden).

Type:

int

enchantability

Likelihood of receiving better enchantments.

Type:

int

repair_ingredient

Item ID used to repair the tool.

Type:

str | None

Example

Creating a ruby pickaxe:

pickaxe = ToolItem(
    id="mymod:ruby_pickaxe",
    name="Ruby Pickaxe",
    durability=500,
    mining_speed_multiplier=8.0,
    attack_damage=3.0,
    mining_level=2,
    enchantability=22,
    repair_ingredient="minecraft:ruby",
)
__init__(id=None, name=None, max_stack_size=1, texture_path=None, durability=0, mining_speed_multiplier=1.0, attack_damage=1.0, mining_level=0, enchantability=0, repair_ingredient=None, recipe=None, item_group=None)[source]

Initialize a new ToolItem instance.

class Block(id=None, name=None, max_stack_size=64, block_texture_path=None, inventory_texture_path=None, recipe=None, item_group=None, left_click_event=None, right_click_event=None, break_event=None, loot_table=None, tool_type=None, hardness=None, resistance=None, mining_level=None, requires_tool=None, mining_speeds=None)[source]

Bases: object

Represents a custom block in a Fabric mod.

The Block class handles the definition of custom blocks including their properties, textures, recipes, and creative tab assignment. Blocks automatically generate corresponding BlockItems for inventory representation.

Mining behaviour is fully configurable through hardness, resistance, tool_type, mining_level, requires_tool, and mining_speeds.

Parameters:
  • id (str | None) – The registry identifier for the block (e.g., “mymod:copper_block”). If None, must be set before compilation.

  • name (str | None) – The display name for the block shown in-game. If None, must be set before compilation.

  • max_stack_size (int) – Maximum number of block items that can be stacked together. Defaults to 64.

  • block_texture_path (str | None) – Path to the block’s texture file for world rendering relative to mod resources. If None, a default texture will be used.

  • inventory_texture_path (str | None) – Path to the texture used for the block’s item form in inventories. If None, falls back to block_texture_path.

  • recipe (object | None) – Recipe definition for crafting this block. Can be a RecipeJson instance or None for no recipe.

  • item_group (object | str | None) – Creative tab to place this block’s item in. Can be an ItemGroup instance, a string constant from item_group module, or None. Typically BUILDING_BLOCKS for most blocks.

  • left_click_event (HookResult) – Java code to execute when the block is left clicked. Can be a string, a list of strings (joined automatically), or None.

  • right_click_event (HookResult) – Java code to execute when the block is right clicked. Can be a string, a list of strings (joined automatically), or None.

  • break_event (HookResult) – Java code to execute after the block is broken/destroyed. The code runs server-side via PlayerBlockBreakEvents.AFTER. Can be a string, a list of strings (joined automatically), or None.

  • loot_table (object | None) – Loot table definition controlling what the block drops when broken. Can be a LootTable instance or None (defaults to dropping itself).

  • tool_type (str | None) – The primary tool required to mine this block efficiently. One of "pickaxe", "axe", "shovel", "hoe", "sword", or None (no specific tool required). Defaults to None.

  • hardness (float | None) – How long the block takes to mine. Lower values break faster. Vanilla reference values: dirt = 0.5, stone = 1.5, obsidian = 50. Defaults to None (uses stone-equivalent 1.5).

  • resistance (float | None) – Blast resistance against explosions. Vanilla reference values: stone = 6.0, obsidian = 1200. Defaults to None (uses stone-equivalent 6.0).

  • mining_level (str | None) – Minimum tool tier needed to mine the block and obtain drops. One of "stone", "iron", "diamond", or None (any tier works). Requires requires_tool=True (or tool_type set) to be effective. Defaults to None.

  • requires_tool (bool | None) – Whether the correct tool must be used for the block to drop items. When None the value is inferred: True if tool_type is set, False otherwise.

  • mining_speeds (dict[str, float] | None) – A mapping of tool type strings (e.g. "pickaxe", "shovel") to custom mining-speed multipliers for this block. When provided, a custom block class is generated that overrides the per-tool break speed, enabling fine-grained control over how fast each tool type mines the block. The block is also automatically added to the mineable/<tool> tags for every key in the dict. Defaults to None.

id

The registry identifier for the block.

Type:

str

name

The display name for the block.

Type:

str

max_stack_size

Maximum stack size for the block item.

Type:

int

block_texture_path

Path to the block’s world texture file.

Type:

str

inventory_texture_path

Path to the block’s inventory texture file.

Type:

str

recipe

Recipe definition for crafting this block.

Type:

RecipeJson

item_group

Creative tab assignment for the block item.

Type:

ItemGroup | str

left_click_event

Java code executed on left click.

Type:

str | list[str] | None

right_click_event

Java code executed on right click.

Type:

str | list[str] | None

break_event

Java code executed after block is broken.

Type:

str | list[str] | None

loot_table

Loot table for block drops (defaults to dropping itself).

Type:

LootTable | None

hardness

Block hardness (mining time).

Type:

float | None

resistance

Blast resistance.

Type:

float | None

mining_level

Minimum tool tier for drops.

Type:

str | None

requires_tool

Whether correct tool is required for drops.

Type:

bool

mining_speeds

Per-tool speed overrides.

Type:

dict[str, float] | None

Example

Creating a basic block:

block = Block(
    id="mymod:copper_block",
    name="Copper Block",
    block_texture_path="textures/blocks/copper_block.png",
    item_group=fabricpy.item_group.BUILDING_BLOCKS
)

Creating a block with mining configuration:

block = Block(
    id="mymod:ruby_ore",
    name="Ruby Ore",
    hardness=3.0,
    resistance=3.0,
    tool_type="pickaxe",
    mining_level="iron",
    requires_tool=True,
)

Creating a block with per-tool mining speeds:

block = Block(
    id="mymod:mixed_ore",
    name="Mixed Ore",
    hardness=4.0,
    resistance=4.0,
    mining_speeds={
        "pickaxe": 8.0,
        "shovel": 3.0,
    },
    requires_tool=True,
    mining_level="stone",
)
__init__(id=None, name=None, max_stack_size=64, block_texture_path=None, inventory_texture_path=None, recipe=None, item_group=None, left_click_event=None, right_click_event=None, break_event=None, loot_table=None, tool_type=None, hardness=None, resistance=None, mining_level=None, requires_tool=None, mining_speeds=None)[source]

Initialize a new Block instance.

Parameters:
  • id (str | None) – The registry identifier for the block.

  • name (str | None) – The display name for the block.

  • max_stack_size (int) – Maximum number of block items that can be stacked.

  • block_texture_path (str | None) – Path to the block’s world texture file.

  • inventory_texture_path (str | None) – Path to the block’s inventory texture file. Falls back to block_texture_path if not provided.

  • recipe (object | None) – Recipe definition for crafting this block.

  • item_group (object | str | None) – Creative tab to place this block’s item in.

  • left_click_event (str | Sequence[str] | None) – Java code to execute when the block is left clicked. Can be a string, a list of strings, or None. Prefer overriding on_left_click() in a subclass.

  • right_click_event (str | Sequence[str] | None) – Java code to execute when the block is right clicked. Can be a string, a list of strings, or None. Prefer overriding on_right_click() in a subclass.

  • break_event (str | Sequence[str] | None) – Java code to execute after the block is broken. Can be a string, a list of strings, or None. Prefer overriding on_break() in a subclass.

  • loot_table (object | None) – Loot table for block drops.

  • tool_type (str | None) – Primary tool type for efficient mining.

  • hardness (float | None) – Block hardness (mining time base).

  • resistance (float | None) – Blast resistance.

  • mining_level (str | None) – Minimum tool tier ("stone", "iron", or "diamond").

  • requires_tool (bool | None) – Whether correct tool is required for drops. Inferred from tool_type when None.

  • mining_speeds (dict[str, float] | None) – Per-tool speed overrides as {tool: speed} mapping.

Raises:

ValueError – If tool_type, mining_level, or any key in mining_speeds is not a recognised value.

on_left_click()[source]

Java code executed when the block is left clicked.

Subclasses can override this to return a string of Java statements, a list of strings (joined automatically), or None. The default implementation returns the value of left_click_event passed to the constructor. ActionResult.SUCCESS is automatically returned, so only include the statements to run when the block is clicked.

Example:

def on_left_click(self):
    return [
        drop_item("DIAMOND", count=3),
        play_sound("EXPERIENCE_ORB_PICKUP"),
        give_xp(25),
    ]
on_right_click()[source]

Java code executed when the block is right clicked.

Subclasses can override this to return a string of Java statements, a list of strings (joined automatically), or None. The default implementation returns right_click_event from the constructor. ActionResult.SUCCESS is automatically returned.

Example:

def on_right_click(self):
    return [
        apply_effect("SPEED", 600, 1),
        play_sound("WITCH_DRINK"),
        send_message("You feel energised!"),
    ]
on_break()[source]

Java code executed after the block is broken (destroyed).

This hook fires server-side after the block has been successfully removed from the world via PlayerBlockBreakEvents.AFTER. The callback receives world, player, pos, state (the block state before breaking), and entity (the BlockEntity, may be null).

Subclasses can override this to return a string of Java statements, a list of strings (joined automatically), or None. The default implementation returns break_event from the constructor.

Example:

def on_break(self):
    return [
        summon_lightning(),
        play_sound("LIGHTNING_BOLT_THUNDER"),
    ]
class ItemGroup(item_id=None, name=None, icon=None, id=None)[source]

Bases: object

Represents a custom creative tab (ItemGroup) in a Fabric mod.

ItemGroups are the tabs shown in the creative inventory that organize items and blocks by category. This class allows creation of custom tabs for mod content.

Parameters:
  • item_id (str) – The registry identifier for the ItemGroup (e.g., “new_foods”). This should be unique and follow mod naming conventions.

  • name (str) – The display name shown to players in the creative inventory. This is used as the language key for localization.

  • icon (Optional[Type]) – The item class or instance whose ItemStack will be displayed as the tab icon. Can be set later using set_icon().

item_id

The unique registry identifier for this ItemGroup.

Type:

str

name

The display name/language key for this ItemGroup.

Type:

str

icon

The item class used as the tab icon.

Type:

Optional[Type]

Example

Creating a food-themed creative tab:

# Create the ItemGroup
food_group = ItemGroup(
    item_id="my_mod_foods",
    name="My Mod Foods"
)

# Set an icon (using an existing item class)
food_group.set_icon(AppleItem)

# Use in item definitions
golden_apple = Item(
    id="mymod:golden_apple",
    name="Golden Apple",
    item_group=food_group
)
__init__(item_id=None, name=None, icon=None, id=None)[source]

Initialize a new ItemGroup.

Parameters:
  • item_id (str) – The registry identifier for the ItemGroup. Should be unique and follow standard mod naming conventions (lowercase, underscores). Can also be passed as ‘id’ for convenience.

  • name (str) – The display name shown in the creative inventory. This will be used as a language key for localization.

  • icon (Type | None) – Optional item class to use as the tab icon. Can be set later using set_icon().

  • id (str) – Alias for item_id. Use either ‘id’ or ‘item_id’, not both.

Raises:

ValueError – If both id and item_id are provided.

Example

Basic ItemGroup creation:

tools_group = ItemGroup(item_id="my_tools", name="My Tools")
# or equivalently:
tools_group = ItemGroup(id="my_tools", name="My Tools")

With initial icon:

weapons_group = ItemGroup(
    id="my_weapons",
    name="My Weapons",
    icon=MySwordItem
)

Note

While None values are technically allowed for error handling scenarios, proper usage requires both an ID and name for the ItemGroup to function correctly in mod compilation.

property id: str

Get the ItemGroup’s ID.

Returns:

The registry identifier for this ItemGroup.

Return type:

str

Note

This is an alias for item_id to maintain compatibility with tests and existing code that expects an ‘id’ property.

property icon_item_id: str | None

Get the item ID of the icon used for this ItemGroup.

Extracts the item ID from the icon object, handling both class attributes and instance attributes.

Returns:

The item ID of the icon, or None if no icon is set

or the icon has no ID attribute.

Return type:

str | None

Example

Getting the icon item ID:

group = ItemGroup(id="weapons", name="Weapons")
group.set_icon(MySwordItem)  # MySwordItem.id = "mymod:sword"
print(group.icon_item_id)    # "mymod:sword"
set_icon(icon)[source]

Set the icon item for this ItemGroup.

The icon appears on the creative inventory tab and should represent the category of items contained within the group.

Parameters:

icon (Type) – The item class whose ItemStack will be displayed as the tab icon. This should be a class that extends Item, FoodItem, or Block.

Example

Setting a custom icon:

magic_group = ItemGroup("magic_items", "Magic Items")
magic_group.set_icon(MagicWandItem)

Note

The icon item should be registered before the ItemGroup is used in mod compilation to ensure proper icon rendering.

__eq__(other)[source]

Check equality with another ItemGroup.

Two ItemGroups are considered equal if they have the same ID, regardless of their name or icon.

Parameters:

other (object) – The object to compare with.

Returns:

True if both objects are ItemGroups with the same ID.

Return type:

bool

Example

Comparing ItemGroups:

group1 = ItemGroup(id="weapons", name="Weapons")
group2 = ItemGroup(id="weapons", name="Combat Items")
print(group1 == group2)  # True (same ID)
__hash__()[source]

Generate a hash value for this ItemGroup.

The hash is based on the ItemGroup’s ID, ensuring that ItemGroups with the same ID have the same hash value.

Returns:

Hash value based on the item_id.

Return type:

int

Note

This allows ItemGroups to be used as dictionary keys and in sets.

class RecipeJson(src)[source]

Bases: object

Wrapper for Minecraft recipe JSON data.

This class holds a validated dictionary representation of a Minecraft recipe along with the original JSON text. It provides validation, convenient property access, and ensures the exact text can be written back to disk unchanged.

Recipes define how items are crafted, smelted, or created through other game mechanics. They must follow Minecraft’s recipe JSON format.

Parameters:

src (str | dict[str, Any]) – Recipe data as either a JSON string or a dictionary. If a string, it will be parsed as JSON. If a dict, it will be used directly and converted to JSON text.

text

The JSON string representation of the recipe.

Type:

str

data

The parsed dictionary representation of the recipe.

Type:

dict[str, Any]

Raises:
  • ValueError – If the recipe is missing a required ‘type’ field or has an invalid ‘type’ value.

  • json.JSONDecodeError – If the input string is not valid JSON.

Example

Creating a recipe from JSON string:

recipe_json = '''
{
    "type": "minecraft:crafting_shaped",
    "pattern": ["##", "##"],
    "key": {"#": "minecraft:stone"},
    "result": {"id": "mymod:stone_block", "count": 1}
}
'''
recipe = RecipeJson(recipe_json)

Creating a recipe from dictionary:

recipe_data = {
    "type": "minecraft:smelting",
    "ingredient": "minecraft:iron_ore",
    "result": "minecraft:iron_ingot",
    "experience": 0.7,
    "cookingtime": 200
}
recipe = RecipeJson(recipe_data)

Getting the result item ID:

result_id = recipe.result_id  # "mymod:stone_block"
__init__(src)[source]

Initialize a new RecipeJson instance.

Parameters:

src (str | dict[str, Any]) – Recipe data as JSON string or dictionary.

Raises:
property result_id: str | None

Get the result item identifier from the recipe.

Extracts the item ID from the recipe’s result field, which is used to name the generated recipe JSON file. Handles both string and dictionary result formats.

Returns:

The result item identifier (e.g., “mymod:stone_block”),

or None if no valid result ID is found.

Return type:

str | None

Example

Getting result ID from different recipe formats:

# String result format
recipe1 = RecipeJson({"type": "minecraft:smelting", "result": "minecraft:iron_ingot"})
print(recipe1.result_id)  # "minecraft:iron_ingot"

# Dictionary result format (1.21+)
recipe2 = RecipeJson({
    "type": "minecraft:crafting_shaped",
    "result": {"id": "mymod:custom_item", "count": 2}
})
print(recipe2.result_id)  # "mymod:custom_item"

# Dictionary result format (pre-1.21)
recipe3 = RecipeJson({
    "type": "minecraft:crafting_shaped",
    "result": {"item": "mymod:legacy_item", "count": 1}
})
print(recipe3.result_id)  # "mymod:legacy_item"
get_result_id()[source]

Get the result ID from the recipe.

This is an alias for the result_id property, provided for backward compatibility and explicit method-style access.

Returns:

The result item identifier, or None if not found.

Return type:

str | None

Example

Using the method-style accessor:

recipe = RecipeJson({"type": "minecraft:smelting", "result": "minecraft:iron_ingot"})
result = recipe.get_result_id()  # "minecraft:iron_ingot"
class LootTable(src, *, loot_type=None, category='blocks')[source]

Bases: object

Wrapper for Minecraft loot-table JSON data.

A LootTable holds a validated dictionary representation of a Minecraft loot table. It can be created from raw JSON, a plain dict, or via convenient class-method builders for common patterns.

The finished object is attached to a Block (via its loot_table attribute) or registered directly with ModConfig for entity / chest loot tables. During compile() the JSON file is written to the appropriate data/<mod_id>/loot_table/ directory.

Parameters:
  • src (str | Dict[str, Any] | List[LootPool]) – Loot-table data as a JSON string, a dictionary, or a list of LootPool builder objects. When pools are passed the loot_type keyword is required.

  • loot_type (str | None) – The "type" field value (e.g. "minecraft:block", "minecraft:entity"). Required when src is a pool list; otherwise inferred from the dict/JSON.

  • category (str) – Sub-directory under loot_table/ when written to disk (e.g. "blocks", "entities", "chests"). Defaults to "blocks".

text

The JSON string representation of the loot table.

Type:

str

data

The parsed dictionary representation.

Type:

dict[str, Any]

category

Sub-directory for file output.

Type:

str

Raises:

Example

Creating a loot table from a dictionary:

lt = LootTable({
    "type": "minecraft:block",
    "pools": [{
        "rolls": 1,
        "entries": [{"type": "minecraft:item", "name": "mymod:my_block"}],
        "conditions": [{"condition": "minecraft:survives_explosion"}]
    }]
})

Using a builder class method:

lt = LootTable.drops_self("mymod:ruby_block")
__init__(src, *, loot_type=None, category='blocks')[source]
property loot_type: str

The type field of the loot table (e.g. "minecraft:block").

property pools: List[Dict[str, Any]]

Return the list of pool dicts.

classmethod drops_self(block_id)[source]

Create a loot table where the block drops itself.

This is the most common loot table pattern — the block simply drops one of itself when broken, subject to explosion protection.

Parameters:

block_id (str) – Registry identifier of the block (e.g. "mymod:ruby_block").

Returns:

A loot table configured for self-drops.

Return type:

LootTable

Example

lt = LootTable.drops_self("mymod:ruby_block")
block = Block(
    id="mymod:ruby_block",
    name="Ruby Block",
    loot_table=lt,
)
classmethod drops_item(block_id, item_id, count=1, *, min_count=None, max_count=None)[source]

Create a loot table where the block drops a specific item.

Parameters:
  • block_id (str) – Registry identifier of the block being broken.

  • item_id (str) – The item to drop.

  • count (int) – Fixed number to drop (used when min_count / max_count are not provided).

  • min_count (int | None) – Minimum items dropped (uniform distribution).

  • max_count (int | None) – Maximum items dropped (uniform distribution).

Returns:

A configured loot table.

Return type:

LootTable

Example

lt = LootTable.drops_item(
    "mymod:ruby_ore", "mymod:ruby", min_count=1, max_count=3,
)
classmethod drops_nothing()[source]

Create an empty loot table (the block drops nothing).

Returns:

A loot table with no pools.

Return type:

LootTable

Example

lt = LootTable.drops_nothing()
classmethod drops_with_silk_touch(block_id, silk_touch_item=None, *, no_silk_touch_item=None, no_silk_touch_count=1)[source]

Create a loot table with silk-touch behaviour.

When mined with Silk Touch the silk_touch_item is dropped (defaults to block_id). When mined without Silk Touch, no_silk_touch_item is dropped if provided, otherwise nothing.

Parameters:
  • block_id (str) – Registry identifier of the block.

  • silk_touch_item (str | None) – Item dropped with Silk Touch. Defaults to block_id.

  • no_silk_touch_item (str | None) – Item dropped without Silk Touch, or None to drop nothing.

  • no_silk_touch_count (int) – How many of the no-silk-touch item to drop.

Returns:

A configured loot table.

Return type:

LootTable

Example

Glass-style — drops itself with silk touch, nothing otherwise:

lt = LootTable.drops_with_silk_touch("mymod:crystal_glass")

Ore-style — silk touch gives ore block, otherwise raw material:

lt = LootTable.drops_with_silk_touch(
    "mymod:ruby_ore",
    no_silk_touch_item="mymod:ruby",
    no_silk_touch_count=1,
)
classmethod drops_with_fortune(block_id, item_id, *, min_count=1, max_count=1, silk_touch_drops_self=True)[source]

Create a fortune-affected loot table (ore-style drops).

Mimics vanilla ore behaviour: without Silk Touch the block drops item_id with fortune scaling; with Silk Touch the block drops itself (if silk_touch_drops_self is True).

Parameters:
  • block_id (str) – Registry identifier of the block.

  • item_id (str) – Item dropped without Silk Touch (e.g. "mymod:ruby").

  • min_count (int) – Minimum base drop count.

  • max_count (int) – Maximum base drop count.

  • silk_touch_drops_self (bool) – Whether Silk Touch drops the block itself.

Returns:

A configured loot table.

Return type:

LootTable

Example

lt = LootTable.drops_with_fortune(
    "mymod:ruby_ore",
    "mymod:ruby",
    min_count=1,
    max_count=2,
)
classmethod entity(pools)[source]

Create an entity loot table from a list of pools.

Parameters:

pools (List[LootPool | Dict[str, Any]]) – List of LootPool builders or raw pool dicts.

Returns:

A loot table with type set to minecraft:entity.

Return type:

LootTable

Example

lt = LootTable.entity([
    LootPool()
        .rolls(1)
        .entry("mymod:monster_fang", weight=1)
        .condition({"condition": "minecraft:survives_explosion"})
])
classmethod chest(pools)[source]

Create a chest loot table from a list of pools.

Parameters:

pools (List[LootPool | Dict[str, Any]]) – List of LootPool builders or raw pool dicts.

Returns:

A loot table with type set to minecraft:chest.

Return type:

LootTable

Example

lt = LootTable.chest([
    LootPool()
        .rolls({"type": "minecraft:uniform", "min": 2, "max": 4})
        .entry("mymod:golden_key", weight=5)
        .entry("minecraft:diamond", weight=1)
])
classmethod from_pools(loot_type, pools, *, category='blocks')[source]

Create a loot table from an arbitrary type and pool list.

Parameters:
  • loot_type (str) – The "type" field (e.g. "minecraft:block").

  • pools (List[LootPool | Dict[str, Any]]) – List of pools (builder objects or dicts).

  • category (str) – Sub-directory for file output.

Returns:

A fully configured loot table.

Return type:

LootTable

class LootPool[source]

Bases: object

Fluent builder for a single loot-table pool.

A pool specifies a set of entries, how many rolls to make, and optional conditions or functions applied to the whole pool.

Example

Building a pool manually:

pool = (
    LootPool()
    .rolls(1)
    .entry("mymod:ruby", weight=3)
    .entry("mymod:sapphire", weight=1)
    .condition({"condition": "minecraft:survives_explosion"})
    .build()
)
__init__()[source]
rolls(value)[source]

Set the number of rolls for this pool.

Parameters:

value (int | Dict[str, Any]) – A fixed integer or a number-provider dict (e.g. {"type": "minecraft:uniform", "min": 1, "max": 3}).

bonus_rolls(value)[source]

Set bonus rolls granted by luck.

Parameters:

value (int | Dict[str, Any]) – A fixed integer or a number-provider dict.

entry(item_id, *, weight=None, quality=None, conditions=None, functions=None)[source]

Add an minecraft:item entry to this pool.

Parameters:
  • item_id (str) – Registry identifier of the item (e.g. "mymod:ruby").

  • weight (int | None) – Relative weight for random selection among entries.

  • quality (int | None) – Luck-based weight modifier.

  • conditions (List[Dict[str, Any]] | None) – Entry-level conditions.

  • functions (List[Dict[str, Any]] | None) – Entry-level item-modifier functions.

raw_entry(entry)[source]

Add any pre-built entry dict (for minecraft:alternatives, etc.).

condition(cond)[source]

Add a pool-level condition.

function(func)[source]

Add a pool-level item-modifier function.

build()[source]

Serialize this pool to a JSON-compatible dict.