Automatically generate API for existing database
using rails 4, you can use the scaffold, taking care to keep the data models exactly the same as the old database (i.e. the same table and column names), and then remove the migrations created with the scaffold.
let's say you have a table called Messages with columns: subject and body.
You can run:
rails g scaffold post subject:string body:text
Then remove the migration from db / migrate.
Now assuming that you have configured your rails app to properly access the database via config / database.yml you should have the json API all set up and ready to use as rails scaffold generates index.json.jbuilder and show.json.jbuilder for every resource that you scaffold.
You may need to edit the application controller to allow external API requests, but this only matters if you plan on POSTing to your API:
if you need POST, then change this line at 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
:
protect_from_forgery with: :null_session
GET requests should work without changing the application controller.
Forgot to mention to access these resources you will be using? format = json as a parameter, so:
http://localhost:3000/posts?format=json
or
http://localhost:3000/posts/1?format=json
Will return json response for all messages or one message.
source to share
you can use AutomaticApiRest [automaticapirest.info] this project was created by me last year. Basically, this tool allows you to create your DB (MySQL) REST APIs in seconds.
Functions
- Build a powerful REST API for your MySQL database in seconds.
- In-Place API Management does not require an additional database.
- Private tables and fields.
- Custom queries.
Installation
-
Download the source or clone the repo.
-
Put it in
/var/www/YourWebPage/
(for Apache). - Open config.php file and fill in all fields with server credencials.
- Go to domain.com/AutomaticaApiRest
source to share