requestFn(...)
The requestFn
is the wrapper on top of the fetch
function that simplifies the process of making requests to the API
using OpenAPI Operation schemas generated by Qraft CLI.
note
The QraftContext
provider requires the requestFn
function to be provided.
With the requestFn
function you can customize the request, add headers, credentials, cache, etc.
import { requestFn } from '@openapi-qraft/react';
const response = await requestFn(
{ url, method, mediaType },
{ baseUrl, parameters, body, meta, ...requestInit }
);
Argumentsโ
schema
- An OpenAPI request schema object with the following properties:url
- The URL of the request, e.g./pet/{pet_id}
method
- The HTTP method of the request, e.g.GET
,POST
,PUT
,DELETE
mediaType
- The media type of the request, e.g.application/json
info
- An object with the following properties:baseUrl
- The base URL of the API, e.g.https://petstore3.swagger.io/api/v3
parameters
- The request parameters, e.g.{ path: { pet_id: 1 }, query: { fields: ['id', 'name'] }, header }
body
- The request body, e.g.{ name: 'doggie', photoUrls: ['https://example.com/doggie.jpg'] }
meta
- The request meta. The purpose is to provide additional information to therequestFn
from the TanStack's hooks...requestInit
- TheRequestInit
object withsignal
,cache
,credentials
,headers
, etc.
Examplesโ
GET
POST
- With
RequestInit
import { requestFn } from '@openapi-qraft/react';
/**
* Executes a GET request:
* ###
* GET https://petstore3.swagger.io/api/v3/pet/1?fields=id&fields=name
*/
await requestFn(
{ url: '/pet/{pet_id}', method: 'GET', mediaType: 'application/json' },
{
parameters: { path: { pet_id: 1 }, query: { fields: ['id', 'name'] },
baseUrl: 'https://petstore3.swagger.io/api/v3',
}
);
import { requestFn } from '@openapi-qraft/react';
/**
* Executes a POST request:
* ###
* POST https://petstore3.swagger.io/api/v3/pet/1?fields=id&fields=name
*
* { "name": "doggie", "photoUrls": ["https://example.com/doggie.jpg"] }
*/
await requestFn(
{ url: '/pet/{pet_id}', method: 'POST', mediaType: 'application/json' },
{
parameters: { path: { pet_id: 1 } },
body: { name: 'doggie', photoUrls: ['https://example.com/doggie.jpg'] },
baseUrl: 'https://petstore3.swagger.io/api/v3',
}
);
import { requestFn } from '@openapi-qraft/react';
// Request cancellation
const controller = new AbortController();
document.addEventListener('customCancelMyRequests', () => {
controller.abort(); // Cancels the request when the event is triggered
});
/**
* Executes a GET request:
* ###
* GET https://petstore3.swagger.io/api/v3/pet/1?fields=id&fields=name
*/
await requestFn(
{ url: '/pet/{pet_id}', method: 'GET', mediaType: 'application/json' },
{
parameters: { path: { pet_id: 1 }, query: { fields: ['id', 'name'] },
baseUrl: 'https://petstore3.swagger.io/api/v3',
signal: controller.signal,
headers: { 'Authorization': `Bearer ...My_Token....` },
credentials: 'omit',
cache: 'no-cache',
}
);