- Notifications
You must be signed in to change notification settings - Fork4
REST APIs for the Best of Us! - A Meteor 0.9+ package for building REST APIshttps://atmospherejs.com/nimble/restivus
License
vatfree/meteor-restivus
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Restivusv1.1.0
NOTE: This package is based onnimble:restivus created byKahmali Rose but has been decaffeinated and expanded.
Restivus makes building REST APIs in Meteor 1.10.0+ easier than ever before! The package is inspiredbyRestStop2 andCollection API,and is built on top ofSimple JSON Routes to provide:
- A simple interface for creating REST APIs
- Easy setup of CRUD endpoints for Mongo Collections
- User authentication via the API
- Optional login and logout endpoints
- Access to
this.user
in authenticated endpoints - Custom authentication if needed
- Role permissions for limiting access to specific endpoints
- Works alongside the
alanning:roles
package - Meteor's accepted rolepermission package
- Works alongside the
- API versioning via URL path
- And also planned:
- JSON PATCH support on collections
- Autogenerated OPTIONS endpoint on routes
- Pre and post hooks on all endpoints
- Getting Started
- Writing a Restivus API
- Consuming a Restivus API
- Upgrading Restivus
- Resources
You can install Restivus using Meteor's package manager:
> meteor add vatfree:restivus
Often, the easiest way to explain something is by example, so here's a short example of what it'slike to create an API with Restivus (keep scrolling for a JavaScript version):
#"Permalink: JavaScript:" href="#javascript">
Items=newMongo.Collection('items');Articles=newMongo.Collection('articles');if(Meteor.isServer){// Global API configurationconstApi=newRestivus({useDefaultAuth:true,prettyJson:true});// Generates: GET, POST on /api/items and GET, PUT, PATCH, DELETE on// /api/items/:id for the Items collectionApi.addCollection(Items);// Generates: POST on /api/users and GET, DELETE /api/users/:id for// Meteor.users collectionApi.addCollection(Meteor.users,{excludedEndpoints:['getAll','put'],routeOptions:{authRequired:true},endpoints:{post:{authRequired:false},delete:{roleRequired:'admin'}}});// Maps to: /api/articles/:idApi.addRoute('articles/:id',{authRequired:true},{get:function(){returnArticles.findOne(this.urlParams.id);},delete:{roleRequired:['author','admin'],action:function(){if(Articles.remove(this.urlParams.id)){return{status:'success',data:{message:'Article removed'}};}return{statusCode:404,body:{status:'fail',message:'Article not found'}};}}});}
Just to clarify some terminology that will be used throughout these docs:
(HTTP) Method:
- The type of HTTP request (e.g., GET, PUT, POST, etc.)
Endpoint:
- The function executed when a request is made at a given URL path for a specific HTTP method
Route:
- A URL path and its set of configurable endpoints
Restivus is aserver-only package. Attempting to access any of its methods from the client willresult in an error.
The following configuration options are available when initializing an API usingnew Restivus(options)
:
- String
- Default:
'api/'
- The base path for your API. If you use
'api'
and add a route called'users'
, the URL will behttps://yoursite.com/api/users/
.
- Object
token
String- Default:
'services.resume.loginTokens.hashedToken'
- The path to the hashed auth token in the
Meteor.user
document. This location will be checkedfor a matching token if one is returned inauth.user()
.
- Default:
user
FunctionDefault: Get user ID and auth token from
X-User-Id
andX-Auth-Token
headersfunction(){return{userId:this.request.headers['x-user-id'],token:Accounts._hashLoginToken(this.request.headers['x-auth-token'])};}
Provides one of two levels of authentication, depending on the data returned. The contextwithin this function is theendpoint context without
this.user
andthis.userId
(well, that's what we're working on here!). Once the user authenticationcompletes successfully, the authenticated user and their ID will be attached to theendpointcontext. The two levels of custom authentication and their required returndata are:- Partial auth
userId
: The ID of the user being authenticatedtoken
: The auth token to be verified- If both a
userId
andtoken
are returned, Restivus will hash the token, then,authentication will succeed if thehashedToken
exists in the givenMeteor.user
document at the location specified inauth.token
- Complete auth
user
: The fully authenticatedMeteor.user
- This is your chance to completely override the user authentication process. If a
user
isreturned, anyuserId
andtoken
will be ignored, as it's assumed that you have alreadysuccessfully authenticated the user (by whatever means you deem necessary). The given useris simply attached to theendpoint context, no questions asked.
For either level of auth described above, you can optionally return a custom error response byproviding that response in an
error
field of your response object. Theerror
value can beany valid response. If anerror
field exists in the object returned fromyour custom auth function, all other fields will be ignored. Donot provide anerror
value if you intend for the authentication to pass successfully.- Partial auth
- Object
- Default:
{ 'Content-Type': 'application/json' }
- The response headers that will be returned from every endpoint by default. These can be overriddenbyreturning
headers
of the same name from any endpoint.
- Endpoint
- Default: undefined
- If an endpoint is provided, it will be used as the OPTIONS endpoint on all routes, except thosethat have one manually defined. This can be used to DRY up your API, since OPTIONS endpoints willfrequentlyrespond generically acrossall routes.
- Boolean
- Default:
true
- If true, enables cross-origin resource sharing (CORS). This allows your API to receive requestsfromany domain (when
false
, the API will only accept requests from the domain where the APIis being hosted.Note: Only applies to requests originating from browsers).
- Function
- Default:
undefined
- A hook that runs once a user has been successfully logged into their account via the
/login
endpoint.Context is the same as within authenticated endpoints. Anyreturned data will be added to the response body asdata.extra
.
- Function
- Default:
undefined
- Same as onLoggedIn, but runs once a user has been successfully logged out of their account viathe
/logout
endpoint.Context is the same as within authenticatedendpoints. Any returned data will be added to the response body asdata.extra
.
- Function
- Default:
undefined
- Function called right after authorization has been checked and before the route
action()
is called. Thiscan be used to add extra checks to the authorization.
- Function
- Default:
undefined
- Function called right before the
action()
on the route is called. This allows to capture all calls to the apiand potentially manipulate the endpoint context that is passed to the route.
- Function
- Default:
undefined
- Function called right before the result is returned to the client. This allows to capture the return valueand potentially manipulate before sending.
- Boolean
- Default:
false
- If
true
, render formatted JSON in response.
- Boolean
- Default:
false
- If
true
,POST /login
andGET /logout
endpoints are added to the API. See [Authenticating](#authenticating) for details on using these endpoints.
- String
- Default:
null
- URL path versioning is the only type of API versioning currently available, so if a version isprovided, it's appended to the base path of all routes that belong to that API
// Base URL path: my-api/v1/ApiV1=newRestivus({apiPath:'my-api/',version:'v1'});// Base URL path: my-api/v2/ApiV2=newRestivus({apiPath:'my-api/',version:'v2'});
Here's a sample configuration with the complete set of options:
Warning! For demo purposes only - using this configuration is not recommended!
newRestivus({apiPath:'my-api/',auth:{token:'auth.apiKey',user:function(){return{userId:this.request.headers['user-id'],token:this.request.headers['login-token']};}},defaultHeaders:{'Content-Type':'application/json'},onLoggedIn:function(){console.log(this.user.username+' ('+this.userId+') logged in');},onLoggedOut:function(){console.log(this.user.username+' ('+this.userId+') logged out');},onAuth:function(auth){// do some extra checks on the `auth.user` objectreturnauth;},onAction:function(){this.extraData='some extra data';},onReturn:function(returnValue){returnreturnValue;},prettyJson:true,useDefaultAuth:true,version:'v1'});
One of the most common uses for a REST API is exposing a set of operations on your collections.Well, you're in luck, because this is almosttoo easy with Restivus! All available REST endpoints(exceptpatch
andoptions
, for now) can be generated for a Mongo Collection usingRestivus#addCollection()
. This generates two routes by default:
/api/<collection>
- Operations on the entire collection
GET
andPOST
/api/<collection>/:id
- Operations on a single entity within the collection
GET
,PUT
,PATCH
andDELETE
The first - and only required - parameter ofRestivus#addCollection()
is a Mongo Collection.Please check out theMeteor docs for more on creatingcollections. TheMeteor.users
collection will have [special endpoints](#users-collection-endpoints) generated.
Route and endpoint configuration options are available inRestivus#addCollection()
(as the 2nd,optional parameter).
The top level properties of the options apply to both routes that will be generated(/api/<collection>
and/api/<collection>/:id
):
- String
- Default: Name of the collection (the name passed to
new Mongo.Collection()
, or'users'
forMeteor.users
) - The base path for the generated routes. Given a path
'other-path'
, routes will be generated at'api/other-path'
and'api/other-path/:id'
- Object
authRequired
Boolean- Default:
false
- If true, all endpoints on these routes will return a
401
if the user is not properlyauthenticated.
- Default:
roleRequired
String or Array of Strings or Object- Default:
undefined
(no role required) - The acceptable user roles for all endpoints on this route (e.g.,
'admin'
,['admin', 'dev']
).Additional role permissions can be defined on specific endpoints. If the authenticated user doesnot belong to at least one of the accepted roles, a403
is returned. Since a role cannot beverified without an authenticated user, setting theroleRequired
impliesauthRequired: true
,so that option can be omitted without any consequence. For more on setting up roles, check outthealanning:roles
package. - If you need to set the scope (or group) of the roleRequired, set this value to an object like:
{roles: 'admin', scope: 'clients'}
or{roles: ['admin', 'finance'], scope: 'clients'}
- Default:
- String or Array of Strings
- Default:
undefined
- The names of the endpoints that shouldnot be generated (see the
endpoints
option below for acomplete list of endpoint names).
- Object
- Default:
undefined
(all available endpoints generated) - Each property of this object corresponds to a REST endpoint. In addition to the
excludedEndpoints
list, you can also prevent an endpoint from being generated by setting itsvalue tofalse
. All other endpoints will be generated. The complete set of configurableproperties on these endpoints is described in theEndpoint Configurationsection below. Here is a list of all available endpoints, including their corresponding HTTP method,path, and a short description of their behavior:getAll
EndpointGET /api/collection
- Return a list of all entities within the collection (filtered searching via query paramscoming soon!).
post
EndpointPOST /api/collection
- Add a new entity to the collection. All data passed in the request body will be copied intothe newly created entity.Warning: This is unsafe for now, as no type or bounds checking isdone.
get
EndpointGET /api/collection/:id
- Return the entity with the given
:id
.
put
EndpointPUT /api/collection/:id
- Completely replace the entity with the given
:id
with the data contained in the requestbody. Any fields not included will be removed from the document in the collection.
patch
EndpointPATCH /api/collection/:id
- Partially modify the entity with the given
:id
with the data contained in the requestbody. Only fields included will be modified.
delete
EndpointDELETE /api/collection/:id
- Remove the entity with the given
:id
from the collection.
By default, each of the endpoints listed above isundefined
, which means it will be generated withany default route options. If you need finer control over your endpoints, each can be defined as anobject containing the following properties:
- Boolean
- Default:
undefined
- If true, this endpoint will return a
401
if the user is not properly [authenticated](#authenticating). If defined, this overrides the option of the same name defined on the entireroute.
- String or Array of Strings
- Default:
undefined
(no role required) - The acceptable user roles for this endpoint (e.g.,
'admin'
,['admin', 'dev']
). These roles will be accepted in addition to any defined over theentire route. If the authenticated user does not belong to at least one of the accepted roles, a403
is returned. Since a role cannot be verified without an authenticated user, setting theroleRequired
impliesauthRequired: true
, so that option can be omitted without anyconsequence. For more on setting up roles, check out thealanning:roles
package.
- Function
- Default:
undefined
(Default endpoint generated) - If you need to completely override the default endpoint behavior, you can provide a functionthat will be executed when the corresponding request is made. No parameters are passed; instead,
this
contains theendpoint context, with properties including the URL andquery parameters.
All responses generated by Restivus follow theJSend format, with one minor tweak: failures havean identical structure to errors. Successful responses will have a status code of200
, unlessotherwise indicated. Sample requests and responses for each endpoint are included below:
Request:
curl -X POST http://localhost:3000/api/articles/ -d"title=Witty Title" -d"author=Jack Rose"
Response:
Status Code:201
{"status":"success","data": {"_id":"LrcEYNojn5N7NPRdo","title":"Witty Title","author":"Jack Rose" }}
Request:
curl -X GET http://localhost:3000/api/articles/
Response:
{"status":"success","data": [ {"_id":"LrcEYNojn5N7NPRdo","title":"Witty Title!","author":"Jack Rose", }, {"_id":"7F89EFivTnAcPMcY5","title":"Average Stuff","author":"Joe Schmoe", } ]}
Request:
curl -X GET http://localhost:3000/api/articles/LrcEYNojn5N7NPRdo
Response:
{"status":"success","data": {"_id":"LrcEYNojn5N7NPRdo","title":"Witty Title","author":"Jack Rose", }}
Request:
curl -X PUT http://localhost:3000/api/articles/LrcEYNojn5N7NPRdo -d"title=Wittier Title" -d"author=Jaclyn Rose"
Response:
{"status":"success","data": {"_id":"LrcEYNojn5N7NPRdo","title":"Wittier Title","author":"Jaclyn Rose" }}
Request:
curl -X PATCH http://localhost:3000/api/articles/LrcEYNojn5N7NPRdo -d"author=J. K. Rowling"
Response:
{"status":"success","data": {"_id":"LrcEYNojn5N7NPRdo","title":"Wittier Title","author":"J. K. Rowling" }}
Request:
curl -X DELETE http://localhost:3000/api/articles/LrcEYNojn5N7NPRdo
Response:
{"status":"success","data": {"message":"Item removed" }}
A few special exceptions have been made for routes added for theMeteor.users
collection. For now,the majority of the operations are limited to read access to theuser._id
and read/write access totheuser.profile
. All route and endpoint options are identical to those described for all othercollections above. No options have been configured in the examples below; however, it is highlyrecommended that role permissions be setup (or at the absolute least, authentication required) forthedelete
endpoint. Below are sample requests and responses for the userscollection.
Create collection:
Api.addCollection(Meteor.users);
Request:POST http://localhost:3000/api/users
{"email":"jack@mail.com","password":"password","profile": {"firstName":"Jack","lastName":"Rose" }}
Note: The only fields that will be recognized in the request body when creating a new user areemail
,username
,password
, andprofile
. These map directly to the parameters of the samename in theAccounts.createUser() method, socheck that out for more information on how those fields are handled.
Response:
Status Code:201
{"status":"success","data": {"_id":"oFpdgAMMr7F5A7P3a","profile": {"firstName":"Jack","lastName":"Rose" } }}
Request:
curl -X GET http://localhost:3000/api/users/
Response:
{"status":"success","data": [ {"_id":"nBTnv83sTrf38fFTi","profile": {"firstName":"Anthony","lastName":"Reid" } }, {"_id":"oFpdgAMMr7F5A7P3a","profile": {"firstName":"Jack","lastName":"Rose" } } ]}
Request:
curl -X GET http://localhost:3000/api/users/oFpdgAMMr7F5A7P3a
Response:
{"status":"success","data": {"_id":"oFpdgAMMr7F5A7P3a","profile": {"firstName":"Jack","lastName":"Rose" } }}
Request:PUT http://localhost:3000/api/users/oFpdgAMMr7F5A7P3a
{"firstName":"Jaclyn","age":25}
Note: The data included in the request body will completely overwrite theuser.profile
field ofthe User document
Response:
{"status":"success","data": {"_id":"oFpdgAMMr7F5A7P3a","profile": {"firstName":"Jaclyn","age":"25" } }}
Request:
curl -X DELETE http://localhost:3000/api/users/oFpdgAMMr7F5A7P3a
Response:
{"status":"success","data": {"message":"User removed" }}
Routes are defined usingRestivus#addRoute()
. A route consists of a path and a set of endpointsdefined at that path.
Thepath
is the 1st parameter ofRestivus#addRoute
. You can pass it a string or regex. If youpass ittest/path
, the full path will behttps://yoursite.com/api/test/path
.
Paths can have variable parameters. For example, you can create a route to show a post with aspecific id. Theid
is variable depending on the post you want to see such as "/articles/1" or"/articles/2". To declare a named parameter in the path, use the:
syntax followed by the parametername. When a user goes to that URL, the actual value of the parameter will be stored as a propertyonthis.urlParams
in your endpoint function.
In this example we have a parameter named_id
. If we navigate to the/post/5
URL in our browser,inside of the GET endpoint function we can get the actual value of the_id
fromthis.urlParams._id
. In this casethis.urlParams._id => 5
.
#"Permalink: JavaScript:" href="#javascript-2">
// Given a URL "/post/5"Api.addRoute('/post/:_id',{get:function(){varid=this.urlParams._id;// "5"}});
You can have multiple URL parameters. In this example, we have an_id
parameter and acommentId
parameter. If you navigate to the URL/post/5/comments/100
then inside your endpoint functionthis.urlParams._id => 5
andthis.urlParams.commentId => 100
.
#"Permalink: JavaScript:" href="#javascript-3">
// Given a URL "/post/5/comments/100"Api.addRoute('/post/:_id/comments/:commentId',{get:function(){varid=this.urlParams._id;// "5"varcommentId=this.urlParams.commentId;// "100"}});
If there is a query string in the URL, you can access that usingthis.queryParams
.
#"Permalink: JavaScript:" href="#javascript-4">
// Given the URL: "/post/5?q=liked#hash_fragment"Api.addRoute('/post/:_id',{get:function(){varid=this.urlParams._id;varquery=this.queryParams;// query.q -> "liked"}});
The following options are available inRestivus#addRoute
(as the 2nd, optional parameter):
- Boolean
- Default:
false
- If true, all endpoints on this route will return a
401
if the user is not properlyauthenticated.
- String or Array of Strings
- Default:
undefined
(no role required) - A string or array of strings corresponding to the acceptable user roles for all endpoints onthis route (e.g.,
'admin'
,['admin', 'dev']
). Additional role permissions can be defined onspecific endpoints. If the authenticated user does not belong to at least one of the acceptedroles, a403
is returned. Since a role cannot be verified without an authenticated user,setting theroleRequired
impliesauthRequired: true
, so that option can be omitted withoutany consequence. For more on setting up roles, check out thealanning:roles
package.
The last parameter ofRestivus#addRoute
is an object with properties corresponding to the supportedHTTP methods. At least one method must have an endpoint defined on it. The following endpoints canbe defined in Restivus:
get
post
put
patch
delete
options
These endpoints can be defined one of two ways. First, you can simply provide a function for eachmethod you want to support at the given path. The corresponding endpoint will be executed when thattype of request is made at that path.
For finer-grained control over each endpoint, you can also define each one as an objectcontaining the endpoint action and some addtional configuration options.
Anaction
is required when configuring an endpoint. All other configuration settings are optional,and will get their default values from the route.
- Function
- Default:
undefined
- A function that will be executed when a request is made for the corresponding HTTP method.
- String
- Default:
Route.authRequired
- If true, this endpoint will return a
401
if the user is not properlyauthenticated. Overrides the option of the same name defined on the entireroute.
- String or Array of Strings
- Default:
Route.roleRequired
- The acceptable user roles for this endpoint (e.g.,
'admin'
,['admin', 'dev']
). These roles will be accepted in addition to any defined over theentire route. If the authenticated user does not belong to at least one of the accepted roles, a403
is returned. Since a role cannot be verified without an authenticated user, setting theroleRequired
impliesauthRequired: true
, so that option can be omitted without anyconsequence. For more on setting up roles, check out thealanning:roles
package.
Api.addRoute('articles',{authRequired:true},{get:{authRequired:false,action:function(){// GET api/articles}},post:function(){// POST api/articles},put:function(){// PUT api/articles},patch:function(){// PATCH api/articles},delete:function(){// DELETE api/articles},options:function(){// OPTIONS api/articles}});
In the above examples, all the endpoints except the GETs will require [authentication](#authenticating).
Each endpoint has access to:
- Meteor.user
- The authenticated
Meteor.user
. Only available ifauthRequired
istrue
and a user issuccessfully authenticated. If not, it will beundefined
.
- String
- The authenticated user's
Meteor.userId
. Only available ifauthRequired
istrue
and a user issuccessfully authenticated. If not, it will beundefined
.
- Object
- Non-optional parameters extracted from the URL. A parameter
id
on the patharticles/:id
would beavailable asthis.urlParams.id
.
- Object
- Optional query parameters from the URL. Given the URL
https://yoursite.com/articles?likes=true
,this.queryParams.likes => true
.
- Object
- Parameters passed in the request body. Given the request body
{ "friend": { "name": "Jack" } }
,this.bodyParams.friend.name => "Jack"
.
- Node response object
- If you handle the response yourself using
this.response.write()
orthis.response.writeHead()
youmust callthis.done()
. In addition to preventing the default response (which will throwan error if you've initiated the response yourself), it will also close the connection usingthis.response.end()
, so you can safely omit that from your endpoint.
Function
Must be called after handling the response manually with
this.response.write()
orthis.response.writeHead()
. This must be called immediately before returning from an endpoint.Api.addRoute('manualResponse',{get:function(){console.log('Testing manual response');this.response.write('This is a manual response');this.done();// Must call this immediately before return!}});
Allendpoint configuration options can be accessed by name (e.g.,this.roleRequired
). Within an endpoint, all options have been completely resolved, meaning allconfiguration options set on an endpoint's route will already be applied to the endpoint asdefaults. So if you setauthRequired: true
on a route and do not set theauthRequired
option onone if its endpoints,this.authRequired
will still betrue
within that endpoint, since thedefault will already have been applied from the route.
You can return a raw string:
return"That's current!";
A JSON object:
return{json:'object'};
A raw array:
return['red','green','blue'];
Or include astatusCode
orheaders
. At least one must be provided along with thebody
:
return{statusCode:404,headers:{'Content-Type':'text/plain','X-Custom-Header':'custom value'},body:'There is nothing here!'};
All responses contain the following defaults, which will be overridden with any provided values:
- Default:
200
- Default:
Content-Type
:application/json
Access-Control-Allow-Origin
:*
- This is aCORS-compliant header that allows requests to be made to the API from anydomain. Without this, requests from within the browser would only be allowed from the samedomain the API is hosted on, which is typically not the intended behavior. This can bedisabled by default, or also byreturning a header of the same name with a domain specified (usually the domain the API isbeing hosted on).
We can't always get an API right on the first try (in fact, most people don't). Eventually, wefind ourselves needing to maintain different versions of our API. This allows clients to convert attheir own convenience, while providing the latest and greatest API to those ready to consume it.
Currently, there is only a single versioning strategy supported in Restivus: URL path versioning. Inthis strategy, the version of the API is appended to the base path of all routes belonging to thatAPI. This allows us to easily maintain multiple versions of an API, each with their own set ofconfiguration options. Here's a [good write-up](http://www.troyhunt.com/2014/02/your-api-versioning-is-wrong-which-is.html) on some of thedifferent API versioning strategies.
// Configure first version of the APIvarApiV1=newRestivus({version:'v1',useDefaultAuth:true,prettyJson:true});// Maps to api/v1/items and api/v1/items/:idApiV1.addCollection(Items,{routeOptions:{authRequired:true}});// Maps to api/v1/customApiV1.addRoute('custom',{get:function(){return'get something';}});// Configure another version of the API (with a different set of config options if needed)varApiV2=newRestivus({version:'v2',enableCors:false});// Maps to api/v2/items and api/v2/items/:id (with auth requirement removed in this version)ApiV2.addCollection(Items);// Maps to api/v2/custom (notice the different return value)ApiV2.addRoute('custom',{get:function(){return{status:'success',data:'get something different'};}});
What's a REST API without awesome docs? I'll tell you: absolutely freaking useless. So to fix that,we use and recommendapiDoc. It allows you to generate beautiful and extremely handy API docsfrom your JavaScript comments. It supports other comment styles as well, but we'reMeteorites, so who cares? Check it out. Use it.
The following uses the above code.
We can call ourPOST /articles/:id/comments
endpoint the following way. Note the /api/ in the URL(defined with the api_path option above):
curl -d"message=Some message details" http://localhost:3000/api/articles/3/comments
Note: There is a 50mb limit on requests. If you need this limit increased, please file a GitHub Issue.
Warning: Make sure you're using HTTPS, otherwise this is insecure!
Note: To use the default authentication, you must firstcreate a user with theaccounts-password
package. You can do this with Restivus if yousetup a POST collection endpoint for theMeteor.users
collection.
If you haveuseDefaultAuth
set totrue
, you now have aPOST /api/login
endpoint that returns auserId
andauthToken
. You must save these, and include them in subsequent requests. In additionto thepassword
, the login endpoint requires one of the following parameters (via the requestbody):
email
: An email address associated with yourMeteor.user
accountusername
: The username associated with yourMeteor.user
accountuser
:Note: This is for legacy purposes only. It is recommended to use one of the optionsabove. Accepts either of the options listed above. Restivus will (very naively) attempt todetermine if the value provided is an email, otherwise it will assume it to be the username. Thiscan sometimes lead to unexpected behavior.
A login will look something like
curl http://localhost:3000/api/login/ -d"username=test&password=password"
The password can be SHA-256 hashed on the client side, in which case your request would look like
curl http://localhost:3000/api/login/ -d"username=test&password=sha-256-password&hashed=true"
And the response will look like
{status:"success",data:{authToken:"f2KpRW7KeN9aPmjSZ",userId:fbdpsNf4oHiX79vMJ}}
You'll need to save theuserId
andtoken
on the client, for subsequent authenticated requests.
You also have an authenticatedPOST /api/logout
endpoint for logging a user out. If successful, theauth token that is passed in the request header will be invalidated (removed from the user account),so it will not work in any subsequent requests.
curl http://localhost:3000/api/logout -X POST -H"X-Auth-Token: f2KpRW7KeN9aPmjSZ" -H"X-User-Id: fbdpsNf4oHiX79vMJ"
For any endpoints that require the default authentication, you must include theuserId
andauthToken
with each request under the following headers:
- X-User-Id
- X-Auth-Token
curl -H"X-Auth-Token: f2KpRW7KeN9aPmjSZ" -H"X-User-Id: fbdpsNf4oHiX79vMJ" http://localhost:3000/api/articles/
To update Restivus to the latest version:
> meteor update vatfree:restivus
Or to update Restivus to a specific version:
> meteor add vatfree:restivus@=<version_number>
For example, to update restivus to v0.7.0:
> meteor add vatfree:restivus@=0.7.0
Please check thechange log before updating, for more information about thechanges between each version. More detailed instructions for updating between major versions areincluded below.
The most noticeable difference in v0.8.0 is that Restivus is now exported as a "class" instead of anobject. API configuration has also been moved fromRestivus.configure()
(which has been removed),to the Restivus constructor. This means that instead of being forced to configure a single RestivusAPI with
Restivus.configure({apiPath:'only-api', ...});Restivus.addRoute('example');
you can configure as many separate APIs as you need with
FirstApi=newRestivus({apiPath:'first-api', ...});SecondApi=newRestivus({apiPath:'second-api', ...});// Maps to /first-api/exampleFirstApi.addRoute('example', ...);// Maps to /second-api/exampleSecondApi.addRoute('example', ...);
This update makes it possible tomaintain multiple versions of an API.
One other significant (but not API-breaking) change is thatiron:router
has beenreplaced bysimple:json-routes
as the server-side router for Restivus. This meansthat Restivus should no longer [interfere with other routers](kahmali#24) (clientor server), or do other [annoying](kahmali#35) [things](kahmali#43). Special thanks to [Sashko Stubailo](https://github.com/stubailo) for his work onsimple:json-routes
, and for handling the conversionfromiron:router
tosimple:json-routes
in Restivus!
Some other notable changes are:
- The
deleteAll
collection endpoint has been removed, as it had the potential to be quitedestructive, and is not a standard REST endpoint useAuth
API config option renamed touseDefaultAuth
- More accurate response codes returned in API
For a complete list of changes, check out the [change log](https://github.com/vatfree/meteor-restivus/blob/devel/CHANGELOG.md#v080---2015-07-06).
Added onAuth, onAction and onReturn functions to global options.
In applications tested, there are no breaking changes between 0.8.x and 1.0.0. The project has beendecaffeinated and all tests have been re-activated, but no functionality has been changed.
WARNING! All clients consuming a Restivus APIwith the default authentication will need toreauthenticate after this update
Restivus used to store the account login token in theMeteor.user
document atservices.resume.loginTokens.token
. Now, to match Meteor's current implementation, the accountlogin token is stored as a hashed token atservices.resume.loginTokens.hashedToken
. This meansthat all clients using the default authentication in a Restivus API will need to reauthenticate withtheir username/email and password after this update, as their existing tokens will be renderedinvalid.
Restivus v0.6.1 brings support for easily generating REST endpoints for your Mongo Collections, andwith that comes a few API-breaking changes:
- The
Restivus.add()
method has been changed toRestivus.addRoute()
for clarity, now that theRestivus.addCollection()
method has been added. - All responses generated by Restivus now follow theJSend format, with one minor tweak: failureshave an identical structure to errors (check out theJSend documentation for more detailson the response structure, which will be demonstrated throughout these docs). Just to be clear,this only affects responses that are automatically generated by Restivus. Any responses youmanually created will remain unaffected.
- Define and generateSwagger 2.0 documentation for Restivus API
A detailed list of the changes between versions can be found in the [change log](https://github.com/vatfree/meteor-restivus/blob/master/CHANGELOG.md).
Contributions to Restivus are welcome and appreciated! If you're interested in contributing, pleasecheck outthe guidelinesbefore getting started.
Thanks to the developers over at Differential forRestStop2, where we got our inspiration forthis package and stole tons of ideas and code, as well as the Sashko Stubailo from MDG, for hiswork onsimple:json-routes
, including the Restivus conversion fromIronRouter.
Also, thanks to the following projects, which RestStop2 was inspired by:
MIT License. SeeLICENSE fordetails.
About
REST APIs for the Best of Us! - A Meteor 0.9+ package for building REST APIshttps://atmospherejs.com/nimble/restivus
Resources
License
Stars
Watchers
Forks
Packages0
Languages
- JavaScript100.0%