schema-api-request
v1.0.6
Published
A web requests fetching json-schemas based tool
Readme
Api-request
The lightweight and simple web api request library based on minimal configuration and json-schemas.
Objectives
- Standartized approach accross all API touching code by a JSONSchema protocol
- Flexibly configure the request/response schemas using metaprogramming
- Configured once, schemas might and should be used both for:
- Swagger creation (like in fastify: link-1 and link-2)
- Shared req/res interfaces accross frontend and backend.
Usage
// A JSON schema for a request
{
"method": "GET",
"url": "/todos/1",
"schema": {
"tags": [
"Rates"
],
"description": "Get placeholder's API 1st todo",
"summary": "Test shcema for api-request",
"requestConfig": {
"baseURL": "https://jsonplaceholder.typicode.com",
"headers": {
"Content-Type": "application/json"
}
},
"response": {
"200": { // Can be extracted to another schema with a $ref here
"type": "object",
"properties": {
"userId": { "type": "number" },
"id": { "type": "number" },
"title": { "type": "string" },
"completed": { "type": "boolean" }
},
"required": ["userId", "id", "title", "completed"]
}
}
}
}Calling directly the request:
import ApiRequest from 'schema-api-request';
import testReqSchema from './schemas/1.schema.json' assert { type: 'json' };
const response = await new ApiRequest(testReqSchema).request();
const data = await response.json();
// Outputs:
// { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
console.log(data);Save and move the request object further:
import ApiRequest from 'schema-api-request';
import testReqSchema from './schemas/1.schema.json' assert { type: 'json' };
const requestObj = new ApiRequest(testReqSchema);
// ...
const response = await requestObj.request();
const data = await response.json();