title: Reduce duplication of model across DB, backend, and frontend
body: <p>I am building a web app using flask (no ORM) backed by a MySQL DB, and React on the frontend. I have a concern in that my model is duplicated in both MySQL, Flask, and React. As an example, say I have the following MySQL table</p>
  
  <pre><code>mysql&gt; CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
  -&gt; species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);
  </code></pre>
  
  <p>Then in the flask app, let's say I wanted to insert into <code>pet</code>. Then the flask view would expect a body with the following fields <code>name</code>, <code>owner</code>, <code>species</code>, <code>sex</code>, <code>birth</code>, and <code>death</code>, and it would also have to know to insert into a schema with fields of those names. So you would need something like <code>body = request.get_json()</code>and then <code>'INSERT INTO pet (name, owner, ...) VALUES ({name}, {owner}, ...)'.format(**body)</code></p>
  
  <p>On the frontend, we would have to maintain a state similar to the backend, like </p>
  
  <pre><code>this.state = {
    name: ...,
    owner: ...,
    ...
  }
  </code></pre>
  
  <p>if let's say these values were coming from a form. And then we would have to POST these values by sending a body like this</p>
  
  <pre><code>{
    name: this.state.name,
    owner: this.state.owner,
    ...
  }
  </code></pre>
  
  <p>In addition to duplication, it seems it is error-prone, as what if the frontend accidentally sent <code>ownerName</code> instead of <code>owner</code>? then the backend tries to parse the body with a field named <code>owner</code> but it doesn't find anything. </p>
  
  <p>Let's say instead that the backend was returning data to the frontend, such as executing <code>SELECT name, owner FROM pet</code>. Then the backend serializes the response into JSON and the frontend has to parse it. The frontend would then need to expect objects with properties called <code>name</code> and <code>owner</code>. If it instead expected i.e <code>petName</code> then this would be a bug.</p>
  
  <p>In summary, the model is duplicated </p>
  
  <ul>
  <li>in the DB Table</li>
  <li>in the backend logic when querying the DB</li>
  <li>in the backend logic when parsing the body of a post request</li>
  <li>in the frontend state</li>
  <li>in the frontend when sending a request body</li>
  <li>in the frontend when rendering a response from the backend</li>
  </ul>
  
  <p>Certainly this issue has been faced by others.</p>