title: CakePHP 4 - custom request and response format
body: <p>For a new project I want to use a CakePHP 4 as REST backend with a Vue.js frontend.<br />
  Now Cake uses a nested data structure while vue.js uses a flat data structure.<br />
  My plan now is to convert the data in the backend.</p>
  <p>Example Format:</p>
  <pre><code>CakePHP
  {
      &quot;user&quot;: {
          &quot;id&quot;: 1,                    
          &quot;name&quot;: &quot;Peter Maus&quot;
          &quot;articles&quot; : [
              {
                  &quot;id&quot;: 15,
                  &quot;title&quot;: &quot;First Post&quot;,
              }
          ]
      },
      
  }
  
  Vue.js
  {
      &quot;user&quot;: {
          &quot;id&quot;: 1,                    
          &quot;name&quot;: &quot;Peter Maus&quot;
          &quot;articles&quot; : [ 15 ]
      },
      &quot;articles&quot;: [
          {
              &quot;id&quot;: 15,
              &quot;title&quot;: &quot;First Post&quot;,
          }
      ]
  }
  </code></pre>
  <p>So basically instead of just sending json with</p>
  <pre><code>$this-&gt;viewBuilder()-&gt;setOption('serialize', ['user']);  
  </code></pre>
  <p>I want to first &quot;convert the datastructure&quot; and then send as json.</p>
  <p>I have now found the following possibilities for the conversion based on the documentation:</p>
  <p><strong>Request</strong> - convert from vue to cake<br />
  I have seen that you can use <a href="https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware" rel="nofollow noreferrer">Body Parser Middleware</a> with your own parser.
  But I still have json as response format and I don't want to override the standard json formatter.</p>
  <p><strong>Response</strong> - convert from cake to vue<br />
  ideas:</p>
  <ul>
  <li><p>I have seen &quot;<a href="https://book.cakephp.org/4/en/views/json-and-xml-views.html#using-a-data-view-with-template-files" rel="nofollow noreferrer">Data Views</a>&quot;, but I'm not sure if it is suitable for this purpose.</p>
  </li>
  <li><p>extend the ViewBuilder and write my own serialize() function.<br />
  How would I have to include my own ViewBuilder, is that even possible?</p>
  </li>
  <li><p>write a parser function in a parent entity from which all my entities inherit. And call that parse function before serializing the data.</p>
  </li>
  </ul>
  <p>I will probably need access to the Entity Relations to dynamically restructure the data, for both: request and response.<br />
  What would be a reasonable approach?</p>