I'm a newbie to node.js trying to create a set of APIs with the loopback framework. My requirement is to accept JSON as an input for my API, and I'm trying to define the same in the model JSON file. As per the official documentation, loopback supports the object
type as an argument type, but I don't see where I can define the JSON object structure. Could someone please let me know how this can be done?
The relevant snippet of the model is as below:
"retrieveProfile": {
"description": "Returns back a particular entity's profile details",
"isStatic": true,
"accepts": [
{
"arg": "msg",
"type": "string",
"http": {
"source": "query"
}
}
],
"returns": {
"arg": "greeting",
"type": "string"
},
"http": {
"verb": "get"
}
}
I figured this one out. You have the define the custom object as a new model in your loopback instance.
Suppose you have the following two models in your loopback instance (this is psuedo code, haven't tested it, but hopefully you'll get the idea):
buildings.json
{
"name": "Buildings",
"properties": {
"name": {
"type": "string"
},
"address": {
"type": "string"
},
"rent": {
"type": "number"
}
}
}
tenants.json
{
"name": "Tenants",
"properties": {
"name": {
"type": "string"
}
}
}
Make sure you declare them in model-config.json
. If you have these models connected to a datasource, this will still work, but they don't have to be connected to a datasource to make this work. I declared them in model-config.json
and then set the datasource as null
.
Then, when you create your remote method, you'd do it like this
buildings.json
{
"name": "Buildings",
...
"methods": {
"chargeRent": {
"accepts": [
{
"arg": "tenant",
"type": "Tenants",
"required": true
}
],
"returns": {
"root": true,
"type": "object"
},
"http": {
"verb": "post"
}
}
}
}
Obviously you can configure your remote method however you want, but the most important part is the type
you define needs to match the name of the model.
Once you've done this, if you look in the Loopback API explorer at this method, you should see that the documentation shows the custom object as an argument for this endpoint. And, depending on how you've defined the properties for the custom object (i.e. required v. not) it'll throw errors if those properties aren't included.
Hope this helps!