title: how to use avro with python to serialize dictionary and write as bytes to bytesio to read and deserialize with schema correctly?
body: <p>I want to use avro to serialize dictionary to produce bytestring, write it to io.BytesIO, read it and deserialize.</p>
  
  <p>Q1: shall I load the schema from avro file as <code>avro.schema.RecordSchema</code> or can i load it from json file as <code>json with json.load</code>? </p>
  
  <p>Q2: when <code>BytesIO</code> used shall I do <code>seek(0)</code> ?</p>
  
  <p>Q3: I use <code>BytesIO</code> just so pass serialized bytestring to read it and deserialize. I want to do this in memory hence why I do not write / read file. is it ok?</p>
  
  <pre><code>import io
  import json
  import avro.io
  import avro.schema
  
  msg = {"name": "foo", "favorite_number": 1, "favorite_color": "pink"}
  
  with open("schema", "rb") as f:
      SCHEMA = avro.schema.parse(f.read())
  
  writer = avro.io.DatumWriter(SCHEMA)
  bytes_writer = io.BytesIO()
  encoder = avro.io.BinaryEncoder(bytes_writer)
  writer.write(msg, encoder)
  b = bytes_writer.getvalue()
  
  reader = avro.io.DatumReader(SCHEMA)
  bytes_reader = io.BytesIO(b)
  decoder = avro.io.BinaryDecoder(bytes_reader)
  deserialized_json = reader.read(decoder)
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>Documentation contains the example with serde and file write/read.
  <a href="https://avro.apache.org/docs/1.8.2/gettingstartedpython.pdf" rel="nofollow noreferrer">https://avro.apache.org/docs/1.8.2/gettingstartedpython.pdf</a></p>
  
  <p>They use <code>DataFileWriter</code> and it does </p>
  
  <pre><code>verify that the items we write are valid items and write the appropriate fields.
  </code></pre>
  
  <p>according to documentation. if I don't use it and use DatumWriter only to write to BytesIO am I doing all ok? The documentation says I can use DatumWriter separately.</p>