I'm trying to post a CSV to one of our API's and import data from it. I took a look at CSVFormat and it looks like it handles the parsing of the CSV and puts the result in an array, which is awesome! However, I'm having some issues when trying to do the POST call.
In my index.php file, I have the supported formats set as follows:
$r->setSupportedFormats('JsonFormat', 'CsvFormat');
However, when I use Postman to send a CSV file to my API, I get the following error:
{
"error": {
"code": 403,
"message": "Content type `multipart/form-data` is not supported."
},
"debug": {
"source": "Restler.php:468 at setup stage",
"stages": {
"success": [],
"failure": [
"get",
"route",
"negotiate",
"message"
]
}
}
}
I tried changing CsvFormat to UploadFormat and it works, but the CSV doesn't get parsed. How can I upload a CSV using POST to my API and have it parsed through CsvFormat?
You need to add both UploadFormat
to supported formats
Your api class can be like
<?php
use Luracast\Restler\Scope;
class Api
{
public function post(array $csv)
{
$parsed_data = Scope::get('CsvFormat')->decode(file_get_contents($csv['tmp_name']));
return $parsed_data;
}
}
You can use a form such as the following to post your csv file
<html>
<body>
<form action="/api" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label><input type="file" name="csv" id="file" /> <br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>