Overview
LoopBack models automaticaly have a standard set of HTTP endpoints that provide REST APIs for create, read, update, and delete (CRUD) operations on model data. The public
property in model-config.json specifies whether to expose the model's REST APIs, for example:
... "MyModel": { "public": true, "dataSource": "db" }, ...
To "hide" the model's REST API, simply change public
to false
.
REST paths
By default, the REST APIs are mounted to the plural of the model name; specifically:
Model.settings.http.path
Model.settings.plural
, if defined inmodels.json
; see 项目结构参考 for more information.- Automatically-pluralized model name (the default). For example, if you have a location model, by default it is mounted to
/locations
.
Using the REST Router
By default, scaffolded applications expose models over REST using the loopback.rest
router.
To manually expose a model over REST with the loopback.rest
router, use the following code, for example:
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.
Request format
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 |
|
|
|
|
Response format
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 } }
Disabling API Explorer
LoopBack API Explorer is great when you're developing your application, but for security reasons you may not want to expose it in production. To disable API Explorer entirely, if you created your application with the Application generator, simply delete or rename server/boot/explorer.js
.
Predefined remote methods
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:
Model API | HTTP Method | Example Path |
---|---|---|
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.
Exposing models
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:
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()
:
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:
module.exports = function(Post) { Post.disableRemoteMethod('__get__tags', false); Post.disableRemoteMethod('__create__tags', false); Post.disableRemoteMethod('__delete__tags', false); };
- 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