Is there any way to automatically generate Rails API for existing database? I have mysql DB from php project and I need to generate REST API for it.
using rails 4, you could use scaffold, taking care to keep the data models exactly like the old database (ie. same table and column names), then remove the migrations that are generated with the scaffold.
let's say you have a table called Posts, with columns: subject and body.
You could run:
rails g scaffold post subject:string body:text
Then remove the migration from db/migrate.
Now assuming you set up the rails app to access the database correctly via config/database.yml, you should have a json API all set up and ready to use, since rails scaffold generates index.json.jbuilder and show.json.jbuilder for each resource that you scaffold.
You might have to edit the application controller to allow external API requests, but this should only matter if you plan on POSTing to your API:
if you do need to POST, then change this line in the top of your app/controllers/application_controller.rb:
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
to this:
protect_from_forgery with: :null_session
GET requests should work without modifying the application controller.
Forgot to mention, to access these resources, you will use ?format=json as a parameter, so:
http://localhost:3000/posts?format=json
or
http://localhost:3000/posts/1?format=json
Will return the json response for all posts or a single post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With