Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an API directly from a data source

I need to create my own REST API. I just saw strongloop and loopback and I thought it will be perfect for my project.

In fact, I was able to get mysql connected using strongloop. However, I had to create something called a "model" and I did it. But, it was like creating a new model from scratch and use it for persisting on the Datasource.

Instead, what I was looking for, is to get a REST API directly from my model on the DB. I mean taking the models from each table on the DB and then set them up as web services.

Is that possible?

I am newbie on these technologies, although I think it is an interesting question.

Thanks

like image 630
ackuser Avatar asked May 26 '26 13:05

ackuser


2 Answers

I'm not sure of a Node tool to do what you're asking, but in other languages / databases you have some choices!

The only one I'm really familiar with is postgrest.

postgrest: You import your data into a Postgres database (similar to MySQL), and it generates a REST API on top of your tables instantly. Bam. Done. I've used this and it was amazingly awesome. You can also deploy it directly on Heroku.

like image 75
rdegges Avatar answered May 30 '26 03:05

rdegges


StrongLoop actually has a "discovery" tool for just this purpose! Read up on that page, but here's the basic code to do it. Just drop this code in a file inside /server/boot/ (the docs are wrong on that, it must be in the directory I mention). Of course, you'll need to tailor it for your use case:

var loopback = require('loopback');
var ds = loopback.createDataSource('mysql', {
  "host": "yourhost",
  "port": 1234,
  "database": "foobar",
  "username": "someuser",
  "password": "somepass"
});

// Discover and build models from a given table
ds.discoverAndBuildModels('PERSON', {visited: {}, associations: true},
function (err, models) {
  // Now we have a list of models keyed by the model name
  // You only need the rest of this if wanted to inspect what came in...

  // For example, you could find the first record from the table
  // and verify info or something.
  models.Person.findOne({}, function (err, person) {
    if(err) {
      // handle this if need be...
      console.error(err);
      return;
    }

    // Some code using `person`

  });
});

Good luck!

like image 21
Jordan Kasper Avatar answered May 30 '26 04:05

Jordan Kasper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!