Sitemap
Locastic

Locastic is an innovative design and development team with more than a decade of experience in transforming creative business ideas into flawless digital products.

Easy CSV export in API Platform

--

Like many other things in ApiPlatform, implementing export to CSV is very simple. Actually, all you need to do is to add a bit of configuration to your route, and additionally, if your entity is not the exact representation of the fields you would like to have in the CSV document, you can create a DTO and DataTransformer which will populate data to fit your needs.

Get Locastic’s stories in your inbox

Join Medium for free to get updates from this writer.

So let’s get started with creating an export for our Order entity:

Press enter or click to view image in full size

The first step is to create a DTO with fields we would like to have in the CSV file. After that, we added the serialization group order-export which will be our normalization-context group for exporting endpoint.

Press enter or click to view image in full size

The next step is to create a DataTransformer which will transform the Order entity into a DTO object:

Press enter or click to view image in full size

Finally, we are ready to create the export route in the Order entity:

Press enter or click to view image in full size

There are a few important things in this configuration:

  • “formats”={“csv”={“text/csv”}} -> Here we set the route format to CSV
  • “pagination_enabled”=false -> In export, we want to show all orders, not just the ones on the first page. Therefore we disabled pagination for this route.
  • “output”=OrderExport::class -> This line is telling ApiPlatform to use the OrderExport DTO we prepared, instead of the Order entity.
  • “normalization_context”={“groups”={“order-export”}} -> Here we set the serialization group we used in DTO

And that’s it! Now we can send a request to /orders/export and we’ll get the CSV. Since we didn’t implement custom export, we can still leverage built-in API Platform features. Therefore we can use all available filters just like we do on regular endpoints for Order entity.

In fact, this is not just a way to make the CSV export — you can use it for any other format too.

Originally published at https://locastic.com on Mar 4, 2020.

--

--

Locastic
Locastic

Written by Locastic

Software solutions for business challenges

Locastic
Locastic

Published in Locastic

Locastic is an innovative design and development team with more than a decade of experience in transforming creative business ideas into flawless digital products.