Обзор
LoopBack модели автоматически имеют стандартный набор HTTP эндпоинтов, который обеспечивает REST APIs операциями CRUD для работы с данными: создание, чтение, обновление и удаление. Публичные свойства в model-config.json указывают следует ли использовать REST APIs в модели, например:
/server/model-config.json
...
"MyModel": {
"public": true,
"dataSource": "db"
},
...
Чтоб “скрыть” REST API модели, просто смените свойство public
на false
.
REST путь
По умолчанию REST APIs используют множественную форму имени модели; а именно:
Model.settings.http.path
Model.settings.plural
, if defined inmodels.json
; см Справочник по компоновки проекта для получения более детальной информации.- Автоматически множественное имя модели (по умолчанию). например, если у вас есть модель - location, по умолчанию она монтируется на
/locations
.
Использование маршрутизатора REST
По умолчанию, базовое приложение использует модель через REST используя loopback.rest
маршрутизатор.
Important:
Если ваше приложение создано с помощью slc loopback
, LoopBack автоматически настроит REST middleware и зарегистрирует публичные модели. Вам не нужно ничего делать дополнительно.
Чтобы вручную подключить модель через REST с помощью loopback.rest
маршрутизатор, используйте следующий код, например:
/server/server.js
var app = loopback();
app.use(loopback.rest());
// Expose the `Product` model
app.model(Product);
After this, the Product
model will have create, read, update, and delete (CRUD) functions working remotely from mobile. At this point, the model is schema-less and the data are not checked.
You can then view generated REST documentation at http://localhost:3000/explorer.
LoopBack provides a number of Built-in models that have REST APIs. See Built-in models REST API for more information.
Формат запроса
For POST and PUT requests, the request body can be JSON, XML or urlencoded format, with the Content-Type header set to application/json, application/xml, or application/x-www-form-urlencoded
. The Accept header indicates its preference for the response format.
The following is an example HTTP request to create a new note:
POST / api / Notes HTTP / 1.1
Host: localhost: 3000
Connection: keep - alive
Content - Length: 61
Accept: application / json
Content - Type: application / json {
"title": "MyNote",
"content": "This is my first note"
}
Passing JSON object or array using HTTP query string
Some REST APIs take a JSON object or array from the query string. LoopBack supports two styles to encode the object/array value as query parameters.
- The syntax from node-querystring (qs)
- Stringified JSON
For example,
http: //localhost:3000/api/users?filter[where][username]=john&filter[where][email]=callback@strongloop.com
http: //localhost:3000/api/users?filter={"where":{"username":"john","email":"callback@strongloop.com"}}
The table below illustrates how to encode the JSON object/array can be encoded in different styles:
JSON object/array for the filter object | qs style | Stringified JSON |
---|---|---|
|
|
|
|
?filter[where][username][inq][0]=john |
|
|
|
|
Формат ответа
The response format for all requests is typically a JSON object/array or XML in the body and a set of headers. Some responses have an empty body. For example,
HTTP / 1.1 200 OK
Access - Control - Allow - Origin: http: //localhost:3000
Access - Control - Allow - Credentials: true
Content - Type: application / json;
charset = utf - 8
Content - Length: 59
Vary: Accept - Encoding
Date: Fri, 24 Oct 2014 18: 02: 34 GMT
Connection: keep - alive {
"title": "MyNote",
"content": "This is my first note",
"id": 1
}
The HTTP status code indicates whether a request succeeded:
- Status code 2xx indicates success
- Status code 4xx indicates request related issues.
- Status code 5xx indicates server-side problems
The response for an error is in the following JSON format:
- message: String error message.
- stack: String stack trace.
- statusCode: Integer HTTP status code.
For example,
{
"error": {
"message": "could not find a model with id 1",
"stack": "Error: could not find a model with id 1\n ...",
"statusCode": 404
}
}
Отключение API Explorer
LoopBack API Explorer полезен, когда вы разрабатываете свое приложение, но с точки зрения безопасности вы навряд ли заточите использовать его в продакшене. Для отключения API Explorer полностью, если вы создовали ваше приложение с помощью Генератора приложения, просто удалите или переименуйте /server/boot/explorer.js
.
Предопределенные удаленные методы
By default, for a model backed by a data source that supports it, LoopBack exposes a REST API that provides all the standard create, read, update, and delete (CRUD) operations.
As an example, consider a simple model called Location
(that provides business locations) to illustrate the REST API exposed by LoopBack. LoopBack automatically creates the following endpoints:
API модели | HTTP Метод | Пример пути |
---|---|---|
create() | POST | /locations |
upsert() | PUT | /locations |
exists() | GET | /locations/:id/exists |
findById() | GET | /locations/:id |
find() | GET | /locations |
findOne() | GET | /locations/findOne |
deleteById() | DELETE | /locations/:id |
count() | GET | /locations/count |
prototype.updateAttributes() | PUT | /locations/:id |
The above API follows the standard LoopBack model REST API that most built-in models extend. See PersistedModel REST API for more details.
Обнаружение модели
To expose a model over REST, set the public property to true in /server/model-config.json
:
...
"Role": {
"dataSource": "db",
"public": false
},
...
Hiding methods and REST endpoints
If you don’t want to expose certain CRUD operations, you can easily hide them by calling disableRemoteMethod()
on the model. For example, following the previous example, by convention custom model code would go in the file common/models/location.js
. You would add the following lines to “hide” one of the predefined remote methods:
common/models/location.js
var isStatic = true;
MyModel.disableRemoteMethod('deleteById', isStatic);
Now the deleteById()
operation and the corresponding REST endpoint will not be publicly available.
For a method on the prototype object, such as updateAttributes()
:
common/models/location.js
var isStatic = false;
MyModel.disableRemoteMethod('updateAttributes', isStatic);
Hiding endpoints for related models
To disable a REST endpoints for related model methods, use disableRemoteMethod().
For example, if there are post and tag models, where a post hasMany tags, add the following code to /common/models/post.js
to disable the remote methods for the related model and the corresponding REST endpoints:
common/models/model.js
module.exports = function(Post) {
Post.disableRemoteMethod('__get__tags', false);
Post.disableRemoteMethod('__create__tags', false);
Post.disableRemoteMethod('__delete__tags', false);
};
REVIEW COMMENT from Rand
- exposing model over rest
- overview
- using the rest router
- must be enabled (app.use(loopback.rest())
- loopback does this by default when you scaffold an app using slc loopback
- how to expose models
- via `server/model.json`
- predefined routes that are exposed
- list of all routes created by loopback
- note some routes are disabled by default for built in models SEE built-in models unexposed models
- exposing built-in models
- overview
- unexposed models
- some routes are not exposed in n models
- app
- exposed routes
- unexposed routes
- why
- user
- exposed routes
- unexposed routes
- why
- role
- exposed routes
- unexposed routes
- why
- rolemapping
- exposed routes
- unexposed routes
- why
- add stuff from bottom built in models rest api section
- exposing user-defined models
- all routes exposed by default
- if you created the model via slc loopback:model
- you expose it over REST during the prompt
- if you created it via discovery...
- if you created it via introspection...
- remote methods
- what are they and why do we use them
- talk about the function signature ALL provided args
- what is context etc
- example
- LINK to custom app logic section
- remote hooks
- what are they and why do we use them
- talk about the function signature ALL provided args
- what is the context object what properties are in it, why its there
- example
- LINK to custom app logic section
- model hooks
- what are they and why do we use them
- basic example
- LINK to custom app logic section