Making a JSON api from a CSV file using fly
download, process, serve, update
- tags
- csv
- flyio
- ruby
- sinatra
Contents
I wanted to be able to serve up and process a CSV file on fly, but have the actual processing of that data happen on the server without any sort of fancy database setup. Here's a way to do it using the persistent volumns.
Bookkeeping
Bookworm has ruby 3.1, so lets use that
|
|
And lets create a quick sintara app:
|
|
config.ru
|
|
app.rb
:
|
|
And then you can run with
|
|
And test
|
|
Hello world
Package the app
Deploy the app
|
|
Test
|
|
|
|
Hello world
Looks good!
Deploy the app
|
|
Inside of the created fly.toml
, lets add a section for a persistent volume:
|
|
Then we can deploy with
|
|
And then test:
|
|
Hello world
Write the logic
Ok, so now that we have something served up, lets actually write the code.
loader.rb
:
|
|
|
|
Hello there DB Exists? false CSV Exists? false DB Exists? false CSV Exists? true
app.rb
:
|
|
|
|
{ "db": "./db", "csv": "./csv", "csv_exists": true, "db_exists": true }
|
|
|
|
{ "csv_exists": true, "db_exists": true }
|
|
{ "count": 73454, "ct": 822, "ny": 3793 }
Deploy new code
Inside of the fly.toml
lets set the DB_DIR
to point to our directory,
and then deploy this sucker!
|
|
Then
|
|
|
|
{ "db": "/data/db", "csv": "/data/csv", "csv_exists": false, "db_exists": false }
Now do a post to set things up
|
|
And then
|
|
{ "count": 73454, "ct": 822, "ny": 3793 }
We can go to the console and stop the machine, and then it will automatically start itself up again when you hit it!
|
|
{ "count": 73454, "ct": 822, "ny": 3793 }
Next steps
When do you want to reload the file? Is it every couple of days? What further transformations do you want to have on the data?
All things to keep playing with.
Previously
Next