ClientRequest Parameters

Request Parameters

When interacting with APIs, you’ll come across different types of parameters that can be passed. You can learn how to define them in an OpenAPI specification in the OpenAPI docs.

In feTS, we provide convenient ways to handle these parameters in your requests. Let’s explore how to work with them.

Path Parameters

Path parameters are variables passed in the URL itself. For example, if the endpoint is /pet/{id}, then id is a path parameter. In feTS Client, you can pass path parameters using the params property in the request parameters object.

path-params.ts
client['/pet/{id}'].get({
  params: {
    id: 1
  }
})

Query Parameters

Query parameters are variables passed in the URL’s query string, starting with a ?. For example, if the URL is /pet?name=Cheddar, then name is a query parameter. In feTS Client, you can pass query parameters using the query property in the request parameters object:

query-params.ts
client['/pet'].get({
  query: {
    name: 'Cheddar'
  }
})

Headers

If an endpoint expects certain headers, you can include them in the headers property of the request parameters object.

headers.ts
client['/my-pets'].get({
  headers: {
    Authorization: 'Bearer 1234567890'
  }
})

JSON Body

When the expected HTTP body is a JSON object with the application/json content type, you can pass it using the json property in the request parameters object:

json-body.ts
client['/add-pet'].post({
  json: {
    name: 'Cheddar',
    description: 'Small cat with a big attitude'
  }
})

Form Data / File Uploads

For expected HTTP body in form data format with multipart/form-data content type, you can pass it using the formData property in the request parameters object. To include a file in form data, create a File object:

form-data.ts
import { readFileSync } from 'fs'
import { File, FormData } from 'fets'
 
// Read a file from the disk and create a new `File` object
const imageFile = new File([readFileSync('cat.jpg')], 'cat.jpg', {
  type: 'image/jpeg'
})
 
// Pass the form data to the POST request
client['/add-pet'].post({
  formData: {
    image: imageFile,
    name: 'Cheddar',
    description: 'Small cat with a big attitude'
  }
})

Request Cancellation

You can use AbortController to cancel a request. Pass the signal property as the second argument to the request:

request-cancellation.ts
const abortCtrl = new AbortController()
 
client['/add-pet'].post({
  json: {
    name: 'Cheddar',
    description: 'Small cat with a big attitude'
  },
  signal: abortCtrl.signal
})
 
// Cancel the request
abortCtrl.abort()

Request Timeout

You can use AbortSignal.timeout to cancel a request. Pass the signal property with AbortSignal.timeout() to the request:

request-timeout.ts
client['/add-pet'].post({
  json: {
    name: 'Cheddar',
    description: 'Small cat with a big attitude'
  },
  signal: AbortSignal.timeout(5000)
})