rest-api-path
v1.1.10
Published
REST Api URL generator
Downloads
71
Readme
URL generator for REST API
This library does not make requests to the API, but only generates data and parameters for the request. Almost exactly the same as 'axios-rest-api', except for axios
. Needed to simplify requests to the REST api from the frontend client. Also adds a query delay feature to test the responsiveness and intuitiveness of the user interface. There are two options for using the library. When you have a single default API server or when you have multiple different API servers/services. In the beginning, it is about using a single server.
Как работает
Just create an API variable and use it where you need it. An instance of a class can be global or extend the capabilities of another library, framework. Created for use in VUE/Nuxt applications extensible via a plugin or Vue.prototype.$api = api;
.
import Api from 'rest-api-path';
let api = new Api(); // resources not specified
const result = api.res('users').get({ id: 123 }); // no data in request
// expect result Equal to
{
method: 'get',
uri: '/users/123',
params: {},
data: null,
seconds: 0,
}
Resource Description
The constructor takes as input an array of resource descriptions for generating API requests. Description of one resource includes Base URL(host), prefix, version, postfix, routing. All fields are optional. You can pass nothing to the input of the constructor. Additionally, it is indicated whether the API interface is public or whether an authorization key/token is needed.
// Resource config
resources.some = {
host: 'http://127.0.0.1',
prefix: 'api',
version: 'v2',
postfix: '',
authorized: false,
key: 'someAuthKey',
delay: 3,
routing: {
route: '',
get: '{id}',
cget: '',
post: '',
delete: '{id}',
put: '{id}',
patch: '{id}',
option: '{id}',
load: '',
send: '',
new: 'new',
save: 'save',
edit: 'edit/{id}',
remove: 'remove/{id}',
},
}
The URL is formed as follows ${host}/${prefix}${version}${postfix}
- host: 'http://127.0.0.1'
- prefix: 'api' - not required
- version: 'v2' - not required
- postfix: 'some' - not required
Total http://127.0.0.1/api/v2/some
and further in accordance with the resource config. You cannot specify routing: { route: 'some/string' }
for all resources of a particular API server in the configuration. You can specify prefix
or postfix
for the server. The ability to explicitly specify a routes
exists only in the context of a particular resource.
Request Methods
In addition to the standard get and post, there are non-canonical cget, load, save, new, edit, remove. Among other things, get implies the presence of the resource ID
as a required parameter of the request by default, because this is a library for requests to the REST API. When you need to simply request a URL without parameters, use the load(null, url)
method as in the example above, or configure your request router.
When you need to make simple GET/POST requests to the server, you don't need this library
Configuration
This means setting default values for most requests, such as base URL
and request templates(routes). You will either have a single default resource or a list of resources that you then need to pass to the class constructor. Configuring URL requests is completely moved to the settings for convenience and ease of use. Although no one forbids you to write full or relative request URLs in methods.
import Api from 'rest-api-path';
const resources = [];
// Default resource.
// Common config for all resources
resources.default = {
host: 'http://127.0.0.1',
prefix: 'api',
};
resources.users = {
routing: {
cget: 'popular',
},
};
var api = new Api(resources);
api.res('users').load(); // GET http://127.0.0.1/api/users
api.res('users').cget(); // GET http://127.0.0.1/api/users/popular
api.res('users').get({id: 1}); // GET http://127.0.0.1/api/users/1
Resources
The basis of requests is to obtain resources from a single or multiple servers. The res(name|url)
method sets the name of the resource or the address of its location. Next, the resource name is matched against a list of configured resources to customize a specific request, if needed. If there are no specific resource settings, the default configuration is taken, and if it is absent, the request will be generated according to generally accepted rules. The method returns a configured instance of the class for further work with the resource.
The resource name is used as-is to be substituted into the final request URL. Therefore, you can not bother with setting up routes, but simply call the resource from the server at a relative address
resources.default = {
host: 'http://127.0.0.1',
prefix: 'api',
};
var api = new Api(resources);
api.res('users/new').post({name: 'Bob'});
// POST http://127.0.0.1/api/users/new
// send data: {name: 'Bob'}
Query Parameters
resoures.google = {
host: 'https://www.google.com',
routing: {
get: 'search',
},
};
var api = new Api(resoures);
api.res('google').load({q: 123, hl: 'ru'});
// GET https://www.google.com/search?q=123&hl=ru
Routing
It is for the ease of calling resources in the library that routing is used. It is assumed that all REST requests to the API are standardized. With a typical server API architecture, you don't even have to set up routing for your resources. The routing setup is a simple JS object with the name of the request method and the request template that redraws the values preset by this library.
URL wildcards are specified in curly braces and are taken from the list of parameters for the request. If there are no substitutions in the template, the parameters will go to the query part of the URL. Some of the parameters can go into substitution, and the rest into URL parameters, if such a situation is necessary.
resources.users = {
host: 'http://127.0.0.1',
routing: {
get: '{id}', // по умолчанию такой же
cget: 'list',
load: 'any/other/user'
},
};
api.res('users').get({id: 1}); // GET http://127.0.0.1/api/users/1
api.res('users').get({id: 1, sort: 'asc'}); // GET http://127.0.0.1/api/users/1?sort=asc
api.res('users').cget(); // GET http://127.0.0.1/api/users/list
api.res('users').post({name: 'Bob'}); // POST http://127.0.0.1/api/users
api.res('users').load({id: 1, sort: 'asc'});
// GET http://127.0.0.1/api/users/any/other/user?id=1&sort=asc
Standard library router. In the comments, the real method of the request sent to the server. Of these, get, post, put, patch, delete, options are generally accepted, the rest are added by the library and are optional.
{
route: resources, // имя ресурса
load: '', // GET
get: '{id}', // GET
cget: '', // GET
send: '', // GET !!!
post: '', // POST
save: '', // POST
remove: '', // POST
new: '', // POST
edit: '', // POST
delete: '{id}', // DELETE
put: '{id}', // PUT
patch: '{id}', // PATCH
option: '{id}', // OPTIONS
}
https://github.com/freedomsex/axios-rest-api/blob/master/Readme.md
Дополнительно
Обработчик запроса
В библиотеке есть служебная возможность установить обработчик запроса. Используется другими библиотеками.
api.builder.requests.setHandler(handler);
Обработчик должен реализовать единственный метод request(config)
в который будут переданы данные для запроса. В таком случае, возвращено будет значение этого метода, а не данные для запроса.
Запрос по URI ресурса
Если нужно получить ресурс по URI при помощи библиотеки, используется метод uri(uri, name)
где name имя API в конфигурации ресурсов. Без указания имени API запрос свормируется с настройками по умолчанию или с настройками ресурса по умолчанию default. uri указывается без хоста, но со всеми остальными атрибутами. Отсутствие префикса или версии, если они указаны в конфиге, вызовет ошибку. Так как uri уже содержит имя ресурса и его ID - их дополнительно указывать не нужно.
resources.some_api = {
host: 'http://127.0.0.1',
prefix: 'api',
};
api.uri('/api/users/123', 'some_api').get(); // GET http://127.0.0.1/api/users/123
api.uri('/api/users/123').get(); // GET /api/users/123
api.uri('/users/123').get(); // GET /api/users/123
api.uri('/users/123', 'some_api').get(); // ERROR - в URI не указан префикс
Опции запроса
api.builder.requests.setOptions - устанавливает options
для всех запросов. В опциях указывается ровно то что требует или необходимо для правильной работы обработчика запросов, например headers
и params
.
api.builder.variables - устанавливает общие переменые variables
для всех обработчиков запросов. Например key
который используется как ключ авторизации для всех запросов. Передаются глобальные variables
при инициализации ресурса.