0

I have a Rails API and my endpoint to load some user info is:

# at user controller
def load_user_info
  user = User.find_by(id: params[:id])
  if user.blank?
    # Here I call an external service to crawl user info from 
    # some webpage, and after get this info I save it in my database
  else
    user
  end
end

In this situation, should my route for load_user_info should be a GET or a POST ?

I already took a look in these two questions, but is not clear enough for me because I only save some data if the user doesn't exist, and if my user doesn't exist is not this method of my controller that will save something in my database, it'll be my external crawler class, this crawler class will get the info from website and than do User.create(attributes), so to my front end page (that will use this API) this endpoint is just responsible to return user info, my client doesn't know about any insert in my database

When do you use POST and when do you use GET?

When should I use GET or POST method? What's the difference between them?

Kyle Heironimus
  • 7,741
  • 7
  • 39
  • 51
Lucas Andrade
  • 4,315
  • 5
  • 29
  • 50
  • 2
    _"But is not clear enough for me"_ – what is unclear in particular? Please be more specific. What does your endpoint do? What makes you think it should be GET, or POST? – Stefan Dec 19 '18 at 14:15
  • @Stefan I updated my description, I think it's more explanatory now – Lucas Andrade Dec 19 '18 at 17:28

3 Answers3

3

Based upon the still limited knowledge I have, I would change the way you are doing this.

Good: Change method to user_info and make it a GET. The fact that it does some extra loading the first time you call it is a side-effect an is not relevant.

Better: Change the method to show (one of the standard Rails methods) and use a GET.

Maybe best: Move the crawl logic to the model or a separate service. Normally, a controller method would not be the best place to do this, but you know your app better than I do.

Kyle Heironimus
  • 7,741
  • 7
  • 39
  • 51
1

You are saving to your database, so for me, logically it's a POST.

Walid Da.
  • 948
  • 1
  • 7
  • 15
1

It will be POST method because you get data from external source in a array and you will extract it and save it to your database. there is no need to use GET method.

rAnA bilAl
  • 36
  • 4
  • _"It will be POST method because [...]"_ – the reason doesn't seem to be obvious to me. Which aspects make it a POST method? (1) get data (2) external source (3) in a array (4) extract it (5) save it (6) database – Stefan Dec 19 '18 at 15:06
  • because he just want to save data in database its simple there is no need to use GET method. – rAnA bilAl Dec 19 '18 at 20:14