Data8 Logo

TypeScript Package

Quickly integrate Data8's web services into your TypeScript code.

Basics

Our types package provides a framework that makes it faster to develop and safer to maintain applications written in TypeScript.

Typed paths for each Data8 web service endpoint enable requests and responses to be checked at compile time, catching mistakes before they reach production. IntelliSense autocomplete for endpoints, request bodies and response shapes increases development speed.

By default, our types package ships only TypeScript type definitions. To turn these types into fully-typed autocompleted API calls, pair the package with openapi-fetch, a client that reads a service's paths and infers the request and response body.

npm install @data8/types openapi-fetch
Configuration

Creating a Client

Each Data8 web service ships as its own namespace in @data8/types. To call one, import the service name from the types package and pass its paths type to openapi-fetch's createClient, along with the base URL for the API call, in this case https://webservices.data-8.co.uk. This gives you a fully-typed client with IntelliSense for every endpoint, request body and response. This can be used across any TypeScript project, as seen in the Data8 TypeScript demo, which uses both Vue.js and React.

import { EmailValidation } from "@data8/types";
import createClient from "openapi-fetch";

const emailClient = createClient<EmailValidation.paths>({
  baseUrl: "https://webservices.data-8.co.uk",
});

The paths type is what links the client to the service's endpoints. Replace EmailValidation with any other service. Find the import name of each service, along with its available endpoints, below.

Service Endpoints
Import Name Endpoints
AddressCaptureValidatePostcodeSimple.json, ValidatePostcode.json, QuickAddressCaptureSimple.json, QuickAddressCapture.json, GetFullAddressSimple.json, GetFullAddress.json, GetFullRawAddressSimple.json, GetFullRawAddress.json, FindAddressSimple.json, FindAddress.json, FindFullAddressSimple.json, FindFullAddress.json, FindFullRawAddressSimple.json, FindFullRawAddress.json, LocalitiesByPostcodeSimple.json, LocalitiesByPostcode.json, LocalitiesByNameSimple.json, LocalitiesByName.json, StreetsByLocalityKeySimple.json, StreetsByLocalityKey.json, StreetsByNameSimple.json, StreetsByName.json, AddressesByStreetKeySimple.json, AddressesByStreetKey.json, AddressesByLocalityKeySimple.json, AddressesByLocalityKey.json, FetchRawAddressSimple.json, FetchRawAddress.json, FetchAddressSimple.json, FetchAddress.json
BankAccountValidationIsValidSimple.json, IsValid.json, IsValidMultiple.json, IBANIsValidSimple.json, IBANIsValid.json, IBANIsValidMultiple.json
BusinessInformationFindBusinessesSimple.json, FindBusinesses.json, SearchBusinesses.json, CreditCheckSimple.json, CreditCheck.json, GetBusinessFinancialsSimple.json, GetBusinessFinancials.json, GetBusinessFinancialsXmlSimple.json, GetBusinessFinancialsXml.json, GetAvailableImageReportsSimple.json, GetAvailableImageReports.json, GetImageReportSimple.json, GetImageReport.json, BusinessSummaryAssistant.json
CompaniesHouseGetCompanyDetailsSimple.json, GetCompanyDetails.json, FindCompanyByNameOrPostcodeSimple.json, FindCompanyByNameOrPostcode.json, FindCompanyByNameAndAddressSimple.json, FindCompanyByNameAndAddress.json, FindCompanyByNameAndAddressMultiple.json
CountryDetectionDetectCountrySimple.json, DetectCountry.json, IPAddressToCountrySimple.json, DetectCountryMultiple.json
CreditCardValidationIsValidSimple.json, IsValid.json, IsValidMultiple.json
CTPSIsCallableSimple.json, IsCallable.json, IsCallableMultiple.json, GetCallableNumberSimple.json, GetCallableNumber.json
DeceasedIsDeceasedSimple.json, IsDeceased.json
DemographicsGetDemographicsSimple.json, GetDemographics.json, GetDemographicsMultiple.json
EircodeGetFullAddressSimple.json, GetFullAddress.json, GetFullRawAddressSimple.json, GetFullRawAddress.json
EmailValidationIsValidSimple.json, IsValid.json, IsValidMultiple.json, CleanseSimple.json, Cleanse.json, CleanseMultiple.json
GoneawayIsGoneawaySimple.json, IsGoneaway.json, IsGoneawayMultiple.json, FindNewAddressSimple.json, FindNewAddress.json, FindNewAddressMultiple.json
InternationalTelephoneValidationIsValidSimple.json, IsValid.json
LocationFindLocationSimple.json, GeocodeSimple.json, FindMyNearestSimple.json, AutoCompleteTownsSimple.json, AutoCompleteTowns.json, FindLocation.json, Geocode.json, FindMyNearest.json, FindLocationMultiple.json, GeocodeMultiple.json, FindMyNearestMultiple.json
MobileValidationIsValidSimple.json, IsValid.json, IsValidMultiple.json
MPSIsMailableSimple.json, IsMailable.json, IsMailableMultiple.json
NameAppendFindResidentsSimple.json, FindResidents.json, FindResidentsMultiple.json, ConfirmResidencySimple.json, ConfirmResidency.json, ConfirmResidencyMultiple.json, FindYearOfBirthSimple.json, FindYearOfBirth.json, FindYearOfBirthMultiple.json
NameCleansingCleanNameSimple.json, CleanName.json, ParseNameSimple.json, ParseName.json
PhoneValidationIsValidSimple.json, IsValid.json
PostcoderCleanAddress.json, CleanAddressSimple.json, CleanAddressDts.json, CleanBusinessAddress.json, CleanBusinessAddressSimple.json, CleanBusinessAddressDts.json
PostcodeVerifyIsValidSimple.json, IsValid.json
PredictiveAddressGetSupportedCountries.json, GetSupportedCountriesAdvanced.json, SearchSimple.json, Search.json, DrillDownSimple.json, DrillDown.json, RetrieveSimple.json, Retrieve.json
SalaciousNameIsUnusableNameSimple.json, IsUnusableName.json, IsUnusableNameMultiple.json
TeleAppendFindTelephoneNumberSimple.json, FindTelephoneNumber.json, FindTelephoneNumberMultiple.json
TeleAppendBusinessFindTelephoneNumberSimple.json, FindTelephoneNumber.json, FindTelephoneNumberMultiple.json
TelephoneDirectoryDirectoryLookupSimple.json, DirectoryLookup.json, DirectoryLookupMultiple.json, DirectoryLookupBusiSimple.json, DirectoryLookupBusi.json, DirectoryLookupBusiMultiple.json
TelephoneFormattingFormatTelephoneNumberSimple.json, FormatTelephoneNumber.json, FormatTelephoneNumberMultiple.json
TelephoneGeocodingGeocodeSimple.json, Geocode.json, GeocodeMultiple.json
TelephoneLineValidationIsValidSimple.json, IsValid.json, IsValidMultiple.json, IsValidAdvancedSimple.json, IsValidAdvanced.json, IsValidAdvancedMultiple.json
TPSIsCallableSimple.json, IsCallable.json, IsCallableMultiple.json, GetCallableNumberSimple.json, GetCallableNumber.json
WebsiteValidationIsValidSimple.json, IsValid.json

Sending a Request

The openapi-fetch client can be used to send requests and handle responses. To do this, data is posted to the client, with an endpoint, in the format client.POST("/ServiceName/Endpoint.json").

Using this format, every request returns { data, error }. An HTTP 200 response from the API populates data, and error is undefined. Any non-200 status - for example an invalid API key - returns error and data is undefined. Both scenarios should be handled.

A 200 response only means the request reached the service, not that the operation succeeded. Therefore, business/validation failures - e.g., a missing email address - should be handled by checking for data.Status.Success.

Since the client was created with ServiceName.paths, attaching the endpoint to it type-checks the body and returned data and enables IntelliSense.

// In production this value should be swapped for an environment variable
const API_KEY = "your_api_key";
async function validateEmail(email: string, fullName: string) {
  const name = toNameRecord(fullName);
  const { data, error } = await emailClient.POST("/EmailValidation/Cleanse.json", {
    headers: { "content-type": "application/json" },
    body: {
      username: "apikey-" + API_KEY,
      email,
      level: "Address",
      record: name ? { Name: name } : undefined,
      options: {
        ParseName: true,
        OutputNameCheck: true,
      },
    },
  });

  if (error) throw new Error(JSON.stringify(error));
  if (!data?.Status?.Success) throw new Error(data?.Status?.ErrorMessage ?? "Data8 request failed");
  return data;
}

To use the sample code, you'll need to get your own API key from your dashboard.

Getting More Control

Components

As well as paths, each service has a components type containing reusable schemas from its API. You can reference these using Service.components["schemas"]["SchemaName"] to type values you build yourself, before making a request.

The example below uses this to type a helper that takes a plain name string and returns a Name object. By annotating the return type as EmailValidation.components["schemas"]["Name"], TypeScript checks the object's shape as you build it and offers autocomplete for its fields:

function toNameRecord(fullName: string): EmailValidation.components["schemas"]["Name"] | undefined {
  const trimmed = fullName.trim();
  if (!trimmed) return undefined;

  const parts = trimmed.split(/\s+/);
  if (parts.length === 1) {
    return { Forename: parts[0] };
  }

  return {
    Forename: parts[0],
    Surname: parts.slice(1).join(" "),
  };
}

Accessing the type of a result

There are two ways to access the type of a result. First by directly accessing it with components:

EmailValidation.components["schemas"]["EmailCleanseOutput"]

Alternatively, you can return the type from your own request function: Awaited<ReturnType<typeof yourRequest>>.

type ValidationResult = Awaited<ReturnType<typeof validateEmail>>;
An error has occurred. This application may no longer respond until reloaded. Reload 🗙