# API

***

## 🖥️ Server Exports

Exports allow other resources to interact with Koja-Crafting directly.

### AddExp Export

**Purpose**: Add experience points to a player programmatically from another resource.

#### Syntax

```lua
exports['koja-crafting']:AddExp(data)
```

#### Parameters

```lua
data = {
    identifier = 'steam:110000XXXXXXXX',  -- Player identifier (optional if playerId provided)
    playerId = 1,                         -- Server ID (optional if identifier provided)
    exp = 100                             -- Amount of XP to add
}
```

| Parameter    | Type   | Required     | Description                                |
| ------------ | ------ | ------------ | ------------------------------------------ |
| `identifier` | String | ⭕ Optional\* | Player's identifier (steam, license, etc.) |
| `playerId`   | Number | ⭕ Optional\* | Player's server ID                         |
| `exp`        | Number | ✅ Required   | Experience points to add                   |

\*One of `identifier` or `playerId` must be provided.

#### Examples

Example 1: Add XP by Player ID

{% code title="example.lua" %}

```lua
-- From your custom resource
exports['koja-crafting']:AddExp({
    playerId = 5,
    exp = 100
})
```

{% endcode %}

Example 2: Add XP by Identifier

{% code title="example.lua" %}

```lua
-- From your custom resource
local playerIdentifier = 'license:6435325123456789'
exports['koja-crafting']:AddExp({
    identifier = playerIdentifier,
    exp = 250
})
```

{% endcode %}

Example 3: Quest Reward

{% code title="quest.lua" %}

```lua
-- In your quest system
function CompleteQuest(playerId, questId)
    -- Your quest completion logic
    
    -- Reward crafting XP
    if questId == 'master_crafter_quest' then
        exports['koja-crafting']:AddExp({
            playerId = playerId,
            exp = 500
        })
    end
end
```

{% endcode %}

Example 4: Job Payout Bonus

{% code title="job.lua" %}

```lua
-- In your job script
RegisterServerEvent('myjob:completeMission')
AddEventHandler('myjob:completeMission', function()
    local source = source
    
    -- Normal job payout
    GivePlayerMoney(source, 5000)
    
    -- Bonus crafting XP
    exports['koja-crafting']:AddExp({
        playerId = source,
        exp = 50
    })
end)
```

{% endcode %}

#### How It Works

1. ✅ Validates player exists in database
2. ➕ Adds XP to player's current total
3. 📈 Automatically calculates level-ups
4. 💾 Saves to database
5. 📢 Notifies player if online

***

### AddBlueprint Export

**Purpose**: Grant a blueprint to a player programmatically from another resource.

#### Syntax

```lua
exports['koja-crafting']:AddBlueprint(identifier, blueprintName)
```

#### Parameters

| Parameter       | Type   | Required | Description                                 |
| --------------- | ------ | -------- | ------------------------------------------- |
| `identifier`    | String | ✅ Yes    | Player's identifier                         |
| `blueprintName` | String | ✅ Yes    | Blueprint item respname (not blueprintItem) |

⚠️ **Important**: Use the item's `respname`, not the `blueprintItem` name!

#### Examples

Example 1: Basic Usage

{% code title="example.lua" %}

```lua
-- From your custom resource
local playerIdentifier = 'license:64376347656789'
exports['koja-crafting']:AddBlueprint(playerIdentifier, 'parachute')
```

{% endcode %}

Example 2: Event Reward

{% code title="example.lua" %}

```lua
-- Event winner gets special blueprint
RegisterServerEvent('myevent:playerWon')
AddEventHandler('myevent:playerWon', function()
    local source = source
    local identifier = GetPlayerIdentifier(source, 0)
    
    exports['koja-crafting']:AddBlueprint(identifier, 'legendary_item')
end)
```

{% endcode %}

Example 3: Shop Purchase

{% code title="shop.lua" %}

```lua
-- In your shop script
function PurchaseBlueprint(playerId, blueprintName, price)
    local identifier = GetPlayerIdentifier(playerId, 0)
    
    if RemovePlayerMoney(playerId, price) then
        exports['koja-crafting']:AddBlueprint(identifier, blueprintName)
        TriggerClientEvent('chat:addMessage', playerId, {
            args = { '[Shop]', 'Blueprint purchased!' }
        })
    end
end
```

{% endcode %}

#### Blueprint Configuration Reference

In your `Config.Craftings`:

{% code title="config.lua" %}

```lua
blueprints = {
    {
        respname = 'parachute',              -- ← Use this in AddBlueprint()
        name = 'Parachute',
        blueprintItem = 'parachute_blueprint', -- ← NOT this
        -- ...
    }
}
```

{% endcode %}

{% hint style="warning" %}
Remember that player can use the item from inventory in ui to learn an blueprint!
{% endhint %}

***

### Place Crafting

**Purpose**: Enter placement mode for portable crafting station.

**Direction**: Server → Client

**When Triggered**:

* Player uses portable crafting item

#### Usage

```lua
-- Server-side
TriggerClientEvent('koja-crafting:client:placeCrafting', playerId, craftingType)
```

#### Parameters

| Parameter      | Type   | Description                      |
| -------------- | ------ | -------------------------------- |
| `playerId`     | Number | Player to trigger placement mode |
| `craftingType` | String | Crafting station type/ID         |
|                |        |                                  |

### <mark style="color:$info;">Using the export in inventory to place a station.</mark>

### OX-INVENTORY

Item definition (ox\_inventory/data/items.lua)

```lua
['weaponcrafting'] = {
  label = 'Weapon Crafting',
  weight = 10,
  craftingType = 'weapon_crafting',
  server = {
    export = 'koja-crafting.place_crafting' -- see bridge below
  }
},
```

### ESX

In **ESX**, you register the item as usable:

```lua
-- server.lua
ESX.RegisterUsableItem('weaponcrafting', function(playerId)
  local xPlayer = ESX.GetPlayerFromId(playerId)
  if not xPlayer then return end

  -- optional: remove item after use
  xPlayer.removeInventoryItem('weaponcrafting', 1)

  -- place crafting station
  exports['koja-crafting']:place_crafting({
    src = xPlayer.source,
    type = 'weapon_crafting',
  })
end)
```

### QB-CORE

In **QB**, create a useable item:

```lua
-- server.lua
QBCore.Functions.CreateUseableItem('weaponcrafting', function(source, item)
    local Player = QBCore.Functions.GetPlayer(source)
    if not Player then return end
    if not Player.Functions.GetItemByName(item.name) then return end

    -- optional: remove item
    Player.Functions.RemoveItem('weaponcrafting', 1)

    -- place crafting station
    exports['koja-crafting']:place_crafting({
        src = source,
        type = 'weapon_crafting',
    })
end)
```

***

## 🔄 Callbacks

Server callbacks for retrieving data.

### koja-crafting:server:checkForBlueprints

**Purpose**: Check player's inventory for blueprint items and automatically unlock them.

**Direction**: Client → Server

**Returns**: Result data with success status and blueprints found.

#### Usage

```lua
-- Client-side
KojaLib.Client.TriggerServerCallback('koja-crafting:server:checkForBlueprints', {}, function(result)
    if result.success then
        print('Blueprints found: ' .. result.blueprintsFound)
        print('Message: ' .. result.message)
    end
end)
```

#### Response Structure

```lua
{
    success = true,                    -- Boolean: Operation success
    message = 'Found 2 new blueprints!', -- String: Result message
    inventory = { ... },               -- Table: Updated inventory
    blueprintsFound = 2                -- Number: Count of new blueprints
}
```

#### Example Integration

{% code title="inventory.lua" %}

```lua
-- In your inventory script
RegisterCommand('checkblueprints', function()
    KojaLib.Client.TriggerServerCallback('koja-crafting:server:checkForBlueprints', {}, function(result)
        if result.success and result.blueprintsFound > 0 then
            ShowNotification('You discovered ' .. result.blueprintsFound .. ' new blueprints!')
        else
            ShowNotification('No new blueprints found.')
        end
    end)
end)
```

{% endcode %}

***

## 🔨 Integration Examples

### Example 1: Quest System Integration

Scenario: Give crafting XP and blueprint as quest reward.

{% code title="quest\_integration.lua" %}

```lua
-- In your quest script (server-side)
RegisterServerEvent('myquest:complete')
AddEventHandler('myquest:complete', function(questId)
    local source = source
    local identifier = GetPlayerIdentifier(source, 0)
    
    if questId == 'blacksmith_apprentice' then
        -- Give crafting XP
        exports['koja-crafting']:AddExp({
            playerId = source,
            exp = 250
        })
        
        -- Give weapon blueprint
        exports['koja-crafting']:AddBlueprint(identifier, 'advanced_weapon')
        
        -- Quest completion message
        TriggerClientEvent('chat:addMessage', source, {
            args = { '[Quest]', 'Crafting skills improved! Blueprint unlocked!' }
        })
    end
end)
```

{% endcode %}

***

## 📚 Related Documentation

* For command usage, see [Commands](broken://pages/0e6ece82256083bf42cd9a7b25d7a0a23d65f57f)
* For player progression details, see [Player Progression](broken://pages/4cab851ea84423a90a1b15aa48e7266fb2c30f98)
* For blueprint configuration, see [Crafting Stations](broken://pages/f456d4c63ebcdd2a50d34776bad5a3d7e3dcf189)
* For server setup, see [Server Settings](broken://pages/165d3835257c8a926c1239cfbd662f1df0c71b1b)

***

## 🆘 Getting Help with Integration

If you need help integrating Koja-Crafting with your scripts:

1. **Check examples above** for similar use cases
2. **Enable debug mode** to see what's happening
3. **Test with simple exports first** before complex integration
4. **Visit Discord**: <https://discord.gg/kojascripts>
5. **Read documentation**: <https://docs.kojascripts.eu>

***

Happy integrating! 🔌

*Remember: Koja-Crafting is designed to be easily integrated with other resources. Use exports for direct control, and events for dynamic updates.*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.kojascripts.eu/new/crafting/configuration/api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
