Setting post parameters in Sinatra with data from an API

664 Views Asked by At

I want to have a GET route that will query an API to collect data, and then redirect to a POST with that data to save to the DB. For example:

get '/query/twitter/company/:name' do
    get_number_of_tweets_for_day( params[:name] )
end

POST '/company/tweets/' do
    company.tweets.create(:date => time_now, :count => num_tweets)
end

How do I set the parameters from the data returned by the function in the GET route, and pass them to the POST route so I can save to the DB?

1

There are 1 best solutions below

0
On

Your code has two completely separate endpoints, which are called in separate API requests. You could make it a single POST request, i.e.:

post '/company/:name/tweets/' do
  num_tweets = get_number_of_tweets_for_day( params[:name] )
  company.tweets.create(:date => time_now, :count => num_tweets)
end

As an alternative, for persisting data between subsequent requests, you would typically use sessions:

enable :sessions

get '/query/twitter/company/:name' do
  session['num_tweets'] = get_number_of_tweets_for_day( params[:name] )
end

post '/company/tweets/' do
  company.tweets.create(:date => time_now, :count => session['num_tweets'])
end

A redirect is not possible from GET to POST, because browsers will keep the request method the same after a redirect. You would have to make your first route a POST too.