NativeScript API Client
A NativeScript module for simply calling HTTP based APIs.
NativeScript Toolbox
This module is part of nativescript-toolbox.
License
Platforms
- Android
- iOS
Installation
Run
tns plugin add nativescript-apiclient
inside your app project to install the module.
Demo
For quick start have a look at the plugin/index.ts or use the "IntelliSense" of your IDE to learn how it works.
Otherwise...
Usage
Import
;
Example
;; ; client.beforeSend .clientError .serverError .success .error .completed; ; for ; userId <= 100; userId++
Routes
Routes are suffixes for a base URL.
You can define one or parameters inside that route, which are replaced when you start a request.
If you create a client like this
;
and start a request like this
client.get;
the client will call the URL
[GET] https://api.example.com/users/5979/profile
Parameter values can also be functions, what means that the value that is returned by that functions is used as value:
; client.get;
A function must have the following structure:
Name | Description |
---|---|
paramName | The name of the parameter. For {id} this will be id |
routeParams | The list of submitted route parameters with their values. IMPORTANT: Keep sure to return strings as values! Otherwise you might have problems to convert the values to an URL part. |
match | The complete (unhandled) expression of the argument. |
formatExpr | The optional format expression of the argument. For {id:number} this will be number . |
funcDepth | This value is 0 at the beginning. If you return a function in that function again, this will increase until you stop to return a function. |
Formatting values
Followed by a :
char a route parameter definition can additionally contain a "format expression".
These expressions can help you to parse and format parameter values.
The first step to do this is to define a so called "format provider" callback in a client:
client.addFormatProvider;
Here we defined the two expressions upper
(convert to upper case chars) and number
(keep sure to have a valid number).
To use them you can define a route like this:
{id:number}/{resource:upper}
Now if you setup your client
;
and start a request like this
client.get;
the client will call the URL
[GET] https://api.example.com/users/5979/PROFILE
The ctx
object in the format provider call of addFormatProvider()
has the following structure:
Authorization
You can submit an optional IAuthorizer
object when you start a request:
The plugin provides the following implementations:
AggregateAuthorizer
;authorizer.addAuthorizersnew ApiClient.BasicAuth"Username", "Password", new ApiClient.BearerAuth"MySecretToken";
BasicAuth
;
BearerAuth
;
OAuth
;authorizer.setField'oauth_field1', 'field1_value';authorizer.setField'oauth_field2', 'field2_value';
TwitterOAuth
;
Requests
GET
// ?TM=5979&MK=23979client.get;
POST
client.post;
PUT
client.put;
PATCH
client.patch;
DELETE
client.delete;
Custom
client.request"FOO", ;
Logging
If you want to log inside your result / error callbacks, you must define one or more logger actions in a client:
; client.addLogger;
Each action receives an object of the following type:
Now you can starts logging in your callbacks:
client.clientError .serverError .success .error .completed;
The IApiClientResult
, IApiClientError
and IApiClientCompleteContext
objects using the ILogger
interface:
URL parameters
You can befine additional parameters for the URL.
If you create a client like this
;
and start a request like this
client.get;
The client will call the URL
[GET] https://api.example.com/users?id=23979&resource=profile
Like route parameters you can also use functions for defining URL parameters:
; client.get;
A function must have the following structure:
Name | Description |
---|---|
paramName | The name of the parameter. For {id} this will be id |
index | The zero based index of the handled URL parameter. |
funcDepth | This value is 0 at the beginning. If you return a function in that function again, this will increase until you stop to return a function. |
IMPORTANT: It is also recommended to use / return strings a parameter values to prevent problems when converting the values to an URL string.
Responses
Callbacks
Simple
client.success;
The result
object has the following structure:
Errors
client.error;
The err
object has the following structure:
Conditional callbacks
You can define callbacks for any kind of conditions.
A generic way to do this is to use the if()
method:
client;
If no condition matches, the callback defined by success()
method is used.
For specific status codes you can use the ifStatus()
method:
client;
Or shorter:
clientstatus500 { // handle the internal server error };
Short hand callbacks
client.clientError; client.ok; client.serverError;
The following methods are also supported:
Name | Description |
---|---|
badGateway | Handles a request with status code 502 . |
badRequest | Handles a request with status code 400 . |
clientOrServerError | Handles a request with a status code between 400 and 599 . |
conflict | Handles a request with status code 409 . |
forbidden | Handles a request with status code 403 . |
gatewayTimeout | Handles a request with status code 504 . |
gone | Handles a request with status code 410 . |
informational | Handles a request with a status code between 100 and 199 . |
insufficientStorage | Handles a request with status code 507 . |
internalServerError | Handles a request with status code 500 . |
locked | Handles a request with status code 423 . |
methodNotAllowed | Handles a request with status code 405 . |
notFound | Handles a request with status code 404 . |
notImplemented | Handles a request with status code 501 . |
partialContent | Handles a request with status code 206 . |
payloadTooLarge | Handles a request with status code 413 . |
redirection | Handles a request with a status code between 300 and 399 . |
serviceUnavailable | Handles a request with status code 503 . |
succeededRequest | Handles a request with a status code between 200 and 299 . |
tooManyRequests | Handles a request with status code 429 . |
unauthorized | Handles a request with status code 401 . |
unsupportedMediaType | Handles a request with status code 415 . |
uriTooLong | Handles a request with status code 414 . |