# Avro Integration

> Learn how to embed Taxi semantic types in Avro schemas and work with Avro data formats

Source: https://taxilang.org/docs/other-api-specs/avro

## Overview

Taxi can enhance Apache Avro schemas with semantic meaning, enabling:
- Semantic typing for Avro records and fields
- Type-safe data serialization and deserialization
- Integration with Avro-based messaging systems

> **Note: Semantic Enhancement**
>
> While Avro describes data structure and serialization, Taxi adds semantic meaning to enable better data discovery and integration across systems.

## Adding Taxi to Avro

### Schema Annotation

Add semantic types to Avro using the `taxi.dataType` attribute:

```json
   {
     "type": "record",
     "namespace": "customer",
     "name": "CustomerRecord",
>    "taxi.dataType": "acme.Customer",
     "fields": [
       {
         "name": "id",
         "type": "string",
>        "taxi.dataType": "acme.CustomerId"
       },
       {
         "name": "email",
         "type": "string",
>        "taxi.dataType": "acme.EmailAddress"
       }
     ]
   }
```

### Auto-Type Generation

If no `taxi.dataType` is specified, Taxi will generate types based on:
- For records: The combination of namespace and name
- For fields: The field name and underlying primitive type

## Declaring Avro in Taxi
You can also describe your Avro model directly in Taxi.  

> **Note: Reccomendation: Add taxi types to Avro schemas when possible**
>
> You can generate these Avro models by hand - but we don't recommend it.
> 
> If you have an Avro schema and can annotate it, it's recommended to annotate that with taxi types, rather than
> duplicating the schema definition as a Taxi model.
> 

### Basic Model Definition

```taxi
import lang.taxi.formats.AvroMessage
import lang.taxi.formats.AvroField

@AvroMessage
model Customer {
   @AvroField(ordinal = 0) 
   id: CustomerId
   
   @AvroField(ordinal = 1) 
   email: EmailAddress?
   
   @AvroField(ordinal = 2) 
   addresses: Address[]
}
```

> **Warning: Field Ordering**
>
> Avro serialization depends on field order. Always specify ordinals using @AvroField to ensure consistent serialization.

### Type Mapping

Taxi automatically maps Avro types to appropriate semantic types:

```taxi
@AvroMessage
model Order {
   // Maps string to semantic type
   @AvroField(ordinal = 0) 
   orderId: OrderId inherits String
   
   // Maps int to semantic type
   @AvroField(ordinal = 1) 
   quantity: Quantity inherits Int
   
   // Maps array to semantic type array
   @AvroField(ordinal = 2) 
   items: OrderItem[]
}
```
