Search code examples
ruby-on-railsdesign-patternsarchitecturesmartphone

Building a backend for mobile and web


i want to build an application that will be accessible from web browsers, and will also be accessible from smartphones.

What is the best way of doing it, those are the 2 option i've thinking about:

  1. Building a rails server that will serve the browsers, and will also be a rest api for the mobile app.

  2. Build a separate rest API server that will be accessible from the mobile app and will also be accessible from the rails web server.

What do you think ? it should be pretty standard i believe. Do you have any more idea for building it ?


Solution

  • Keep it with 1 app server (running Rails)

    --

    API

    Rails has a very strong structure, which you can use to create a RESTful API quite simply:

    #config/routes.rb
    namespace :api do
       resources :posts #-> domain.com/api/posts
    end
    
    #app/controllers/api/posts_controller.rb
    Class API::PostsController < ApplicationController
       respond_to :json
       # ... your methods here
    end
    

    This will allow you to send the requests you need

    --

    MIME Types

    The second part of this is about mime types, as stated by snarf. Rails, through the ActionDispatch::Http::MimeNegotiation middleware, allows you to handle different types of request, providing you the ability to handle an api in the most efficient way

    This means you can only allow json requests to your api controller - meaning that when you develop your mobile app, you can send the api requests to your Rails server, rather than a separate API one.

    --

    Recommendation

    I would highly recommend using a single server, running rails

    There are several reason for this:

    1. Creating an API in Rails is actually quite simple
    2. Using one server allows you to handle all the data in one place
    3. Keeping a single server also ensures user authenticity across all platforms