What is the difference between a regular Rails app and a Rails API?

前端 未结 3 606
时光取名叫无心
时光取名叫无心 2021-01-02 18:58

In the process of learning Rails, I read about how we could combine it with some front-end MV* JavaScript frameworks — such as Backbone.js, Angular.js, or Ember.js — to impr

3条回答
  •  Happy的楠姐
    2021-01-02 19:32

    A regular Rails app will use the rails views (erb or haml) to render pages directly. That is to say, it will process the data AND render this data in views, answering directly the client request with a HTML page.

    A Rails API will just process your action, and assume someone else is doing the job of rendering the view for the client. Therefore, a Rails API is expected to return data in an appropriate format, like JSON, XML, or just a JS piece of code to execute. It is then the job of frontend frameworks like AngularJS to receive, parse, and do something with the data (like update some HTML, etc.)

    In a nutshell,

    • Classic Rails application are all-in-one applications, where the processing and rendering are both handled by Rails. The apps may lack or responsiveness however, as full pages are rendered, but it's usually much faster to code this way.
    • Rails API are just serving intermediate results. It will focus on just delivering the data. This can be better if you have strong requirements for the design/responsiveness, as you are more flexible with the frontend libraries you can use. Usually only the data is transferred, so in addition it can be faster. There are some problems with APIs. For example with one-page apps + full AJAX, it may be harder to set up a forward/back behavior on the user browser. Also, using APIs will require more work, but if you have many devs, you can agree on the interfaces, and parallelize the work server/frontend.

    Now, it's not a black or white answer I'm giving. You can totally have a Rails app mainly built as a Web app, but with some API actions that give more responsiveness to some pages. An exemple of this, is to have an autocomplete form, that is pulling the data via AJAX calls.

提交回复
热议问题