Skip to content

Created/edited by GitHub Copilot; pending human review.

Client reference ​

This page describes how to create a client with @sefaria/api-client and set its options. It also describes the error for a response that doesn't match its contract, the validation helpers, and the generated API functions.

Which release this describes ​

This page documents the code on the main branch. The source stamp is not an npm release or a development snapshot. This copy was built from commit 6fde603.

Install an exact npm version or use a version-pinned npm CDN module. The npm alpha tag moves between reviewed prereleases. It is not a main-build snapshot. Older pinned releases keep their own behavior and can lack APIs added since. Install and status lists package commands and jsDelivr/UNPKG files.

Client, options, errors and validation ​

These names are written by hand. Import them from the package root. You can also import some from subpaths:

  • SefariaCacheOptions, SefariaClient, SefariaClientOptions, createSefariaClient, requireSefariaClient from @sefaria/api-client/client.
  • ContractIssue, SefariaContractError, SefariaContractErrorOptions from @sefaria/api-client/errors.
  • GeneratedResponseContract, ResponseSelector, ResponseValidationContext, ResponseValidatorLookup, ValidationResult, getResponseContract, getResponseValidator, validateExternalResponse, validateResponse from @sefaria/api-client/validation.

Functions ​

createSefariaClient() ​

ts
function createSefariaClient(options?): SefariaClient;

Creates a frozen generated-SDK client with status-aware response validation.

Documented HTTP error statuses resolve through the generated typed error payloads. A response that violates the generated contract rejects with SefariaContractError. Fetch network failures and aborts reject with the original error.

Parameters ​
ParameterType
optionsSefariaClientOptions
Returns ​

SefariaClient


getResponseContract() ​

ts
function getResponseContract(selector): GeneratedResponseContract | undefined;

Returns the generated contract matching an exact method, path, and status.

Parameters ​
ParameterType
selectorResponseSelector
Returns ​

GeneratedResponseContract | undefined


getResponseValidator() ​

ts
function getResponseValidator(
  contract,
): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined;

Returns the Zod schema attached to a generated response contract.

Parameters ​
ParameterType
contractGeneratedResponseContract
Returns ​

| ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined


validateExternalResponse() ​

ts
function validateExternalResponse(selector, value, lookup?): ValidationResult;

Validates externally supplied JSON without throwing or requiring a Response.

Parameters ​
ParameterTypeDefault value
selectorResponseSelector—
valueunknown—
lookupResponseValidatorLookupgetResponseValidator
Returns ​

ValidationResult

Classes ​

SefariaContractError ​

Error thrown when a Sefaria response violates its generated contract.

Extends ​
  • Error
Constructors ​
Constructor ​
ts
new SefariaContractError(options): SefariaContractError;
Parameters ​
ParameterType
optionsSefariaContractErrorOptions
Returns ​

SefariaContractError

Overrides ​
ts
Error.constructor;
Properties ​
PropertyModifierTypeDescription
issuesreadonlyreadonly ContractIssue[]Structured validation failures.
methodreadonlystringHTTP method from the generated operation contract.
operationIdreadonlystringGenerated OpenAPI operation identifier.
pathreadonlystringGenerated operation path template.
responsereadonlyResponseOriginal response, preserved for headers and transport metadata.
statusreadonlynumberReceived HTTP status code.

Interfaces ​

SefariaClientOptions ​

Configuration used to create an isolated Sefaria API client.

Properties ​
PropertyModifierTypeDescription
baseUrl?readonlystringAPI origin. Defaults to https://www.sefaria.org.
cache?readonlyfalse | SefariaCacheOptionsBounded per-client response caching. Enabled with defaults when omitted.
fetch?readonly(input, init?) => Promise<Response>Fetch implementation used for requests, testing, or host integration.

SefariaCacheOptions ​

Limits for one client's bounded in-memory response cache.

Properties ​
PropertyModifierTypeDescription
maxBytes?readonlynumberPositive integer maximum decoded response-body bytes retained by one client. Defaults to 10 MiB.
maxEntries?readonlynumberPositive integer maximum number of admitted responses retained by one client. Defaults to 100.
ttlMs?readonlynumberPositive finite time-to-live in milliseconds for an admitted response. Defaults to five minutes.

SefariaClient ​

Branded client accepted by the generated Sefaria SDK operations.

Properties ​
PropertyModifierTypeDescription
[sefariaClientBrand]readonlytrueCompile-time brand preventing accidental structural substitutes.
clearCachereadonly() => voidRemoves all responses retained by this client.
getreadonly<TData, TError, ThrowOnError>(options) => RequestResult<TData, TError, ThrowOnError, "fields">Performs a validated GET request using fields-style responses. A fields-style result exposes the response payload on data, a documented error payload on error, and the original Fetch Response metadata on response. Documented HTTP error statuses resolve as typed error payloads. Contract mismatches reject with SefariaContractError; network failures and aborts reject with the original error.
postreadonly<TData, TError, ThrowOnError>(options) => RequestResult<TData, TError, ThrowOnError, "fields">Performs a validated POST request using fields-style responses. A fields-style result exposes the response payload on data, a documented error payload on error, and the original Fetch Response metadata on response. Documented HTTP error statuses resolve as typed error payloads. Contract mismatches reject with SefariaContractError; network failures and aborts reject with the original error.

ContractIssue ​

One structured response-contract mismatch.

Properties ​
PropertyModifierTypeDescription
instancePathreadonlystringJSON Pointer into the received response value.
keywordreadonlystringValidator keyword or synthetic contract failure category.
message?readonlystringHuman-readable diagnostic supplied by the validator.
schemaPathreadonlystringJSON Pointer identifying the generated schema location.

GeneratedResponseContract ​

Properties ​
PropertyModifierType
bodyTypereadonly"blob" | "json"
contentTypesreadonlyreadonly string[]
functionNamereadonlystring
methodreadonly"GET" | "POST"
operationIdreadonlystring
pathreadonlystring
schema?readonlyZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>
schemaPathreadonlystring
statusreadonlynumber
validatorName?readonlystring

ResponseSelector ​

Identifies one documented operation response by method, path, and status.

Properties ​
PropertyModifierTypeDescription
methodreadonlystringHTTP method; matching is case-insensitive.
pathreadonlystringGenerated OpenAPI path template rather than a concrete request URL.
statusreadonlynumberHTTP response status code.

SefariaContractErrorOptions ​

Complete context retained by SefariaContractError.

Properties ​
PropertyModifierTypeDescription
issuesreadonlyreadonly ContractIssue[]Structured validation failures.
methodreadonlystringHTTP method from the generated operation contract.
operationIdreadonlystringGenerated OpenAPI operation identifier.
pathreadonlystringGenerated operation path template.
responsereadonlyResponseOriginal response, preserved for headers and transport metadata.
statusreadonlynumberReceived HTTP status code.

Type Aliases ​

ResponseValidatorLookup ​

ts
type ResponseValidatorLookup = (contract) => ZodType | undefined;

Resolves the runtime schema used for one generated response contract.

Parameters ​
ParameterType
contractGeneratedResponseContract
Returns ​

ZodType | undefined


ValidationResult ​

ts
type ValidationResult =
  | {
      issues: readonly [];
      valid: true;
    }
  | {
      issues: readonly ContractIssue[];
      valid: false;
    };

Non-throwing validation result for externally supplied response-shaped JSON.

Generated functions by namespace ​

The client has 60 generated functions, one for each endpoint in the corrected API description. The functions are grouped into namespaces that follow the sections of Sefaria's API, and each namespace is exported from the package root. Call a function with a client and its request options, for example text.getV3Texts({ client, path: { tref: "Micah 6:8" } }).

  • Options type describes the path, query, and body options that the function accepts.
  • Responses type maps each documented success status to its response body. Errors type, where there is one, does the same for documented error statuses.
  • Validators check a response body for one status. The client runs them on the responses it receives. You can also call them on JSON from elsewhere.
  • A binary response has no validator. The client checks only its status and content type.

text ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
text.getV3TextsGET /api/v3/texts/{tref}Texts (v3)GetV3TextsDataGetV3TextsResponsesGetV3TextsErrorsvalidateGetV3Texts200 (200)
validateGetV3Texts400 (400)
validateGetV3Texts404 (404)
text.getV1TextsGET /api/texts/{tref}Texts (v1)GetV1TextsDataGetV1TextsResponses—validateGetV1Texts200 (200)
text.getTranslationsGET /api/texts/translationsLanguagesGetTranslationsDataGetTranslationsResponses—validateGetTranslations200 (200)
text.getTranslationsLangGET /api/texts/translations/{lang}TranslationsGetTranslationsLangDataGetTranslationsLangResponses—validateGetTranslationsLang200 (200)
text.getManuscriptsGET /api/manuscripts/{tref}ManuscriptsGetManuscriptsDataGetManuscriptsResponses—validateGetManuscripts200 (200)
text.getTextsRandomGET /api/texts/randomRandom TextGetTextsRandomDataGetTextsRandomResponses—validateGetTextsRandom200 (200)
text.getBulktextGET /api/bulktext/{refs}—GetBulktextDataGetBulktextResponses—validateGetBulktext200 (200)
text.getPassagesGET /api/passages/{refs}—GetPassagesDataGetPassagesResponses—validateGetPassages200 (200)
text.getTextVersionsGET /api/texts/versions/{tref}VersionsGetTextVersionsDataGetTextVersionsResponses—validateGetTextVersions200 (200)

index ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
index.getV2IndexGET /api/v2/raw/index/{index_title}Index (v2)GetV2IndexDataGetV2IndexResponses—validateGetV2Index200 (200)
index.getIndexGET /api/indexTable of ContentsGetIndexDataGetIndexResponses—validateGetIndex200 (200)
index.getShapeGET /api/shape/{title}ShapeGetShapeDataGetShapeResponses—validateGetShape200 (200)
index.getAuthorIndexesGET /api/authors/{author_slug}/indexes—GetAuthorIndexesDataGetAuthorIndexesResponses—validateGetAuthorIndexes200 (200)
index.getIndexTitlesGET /api/index/titles—GetIndexTitlesDataGetIndexTitlesResponses—validateGetIndexTitles200 (200)
index.getIndexByTitleGET /api/index/{title}—GetIndexByTitleDataGetIndexByTitleResponses—validateGetIndexByTitle200 (200)
index.getIndexV2GET /api/v2/index/{title}—GetIndexV2DataGetIndexV2Responses—validateGetIndexV2200 (200)
index.getCountsGET /api/counts/{title}—GetCountsDataGetCountsResponses—validateGetCounts200 (200)
index.getCountsLinksGET /api/counts/links/{cat1}/{cat2}—GetCountsLinksDataGetCountsLinksResponses—validateGetCountsLinks200 (200)
index.getCountsWordsGET /api/counts/words/{title}/{version}/{language}—GetCountsWordsDataGetCountsWordsResponses—validateGetCountsWords200 (200)
FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
related.getRelatedGET /api/related/{tref}RelatedGetRelatedDataGetRelatedResponses—validateGetRelated200 (200)
related.getRelatedWebsitesGET /api/related/{tref}/websitesRelated Web PagesGetRelatedWebsitesDataGetRelatedWebsitesResponses—validateGetRelatedWebsites200 (200)
related.getLinksGET /api/links/{tref}LinksGetLinksDataGetLinksResponsesGetLinksErrorsvalidateGetLinks200 (200)
validateGetLinks400 (400)
related.getRefTopicLinksGET /api/ref-topic-links/{tref}Ref-Topic-LinksGetRefTopicLinksDataGetRefTopicLinksResponses—validateGetRefTopicLinks200 (200)
related.getLinkSummaryGET /api/link-summary/{ref}—GetLinkSummaryDataGetLinkSummaryResponses—validateGetLinkSummary200 (200)

calendars ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
calendars.getCalendarsGET /api/calendarsCalendarsGetCalendarsDataGetCalendarsResponses—validateGetCalendars200 (200)
calendars.getNextReadGET /api/calendars/next-read/{parasha}Next ReadGetNextReadDataGetNextReadResponses—validateGetNextRead200 (200)
calendars.getAliyotByParashaGET /api/sheets/{parasha}/get_aliyot—GetAliyotByParashaDataGetAliyotByParashaResponses—validateGetAliyotByParasha200 (200)
calendars.getCalendarParashaTopicGET /api/calendars/topics/parasha—GetCalendarParashaTopicDataGetCalendarParashaTopicResponses—validateGetCalendarParashaTopic200 (200)
calendars.getCalendarHolidayTopicGET /api/calendars/topics/holiday—GetCalendarHolidayTopicDataGetCalendarHolidayTopicResponses—validateGetCalendarHolidayTopic200 (200)

lexicon ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
lexicon.getWordsGET /api/words/{word}LexiconGetWordsDataGetWordsResponses—validateGetWords200 (200)
lexicon.getWordsCompletionGET /api/words/completion/{word}/{lexicon}Word CompletionGetWordsCompletionDataGetWordsCompletionResponses—validateGetWordsCompletion200 (200)

topic ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
topic.getV2TopicsGET /api/v2/topics/{topic_slug}Topic (v2)GetV2TopicsDataGetV2TopicsResponses—validateGetV2Topics200 (200)
topic.getTopicSlugGET /api/topics/{topic_slug}Topic (v1)GetTopicSlugDataGetTopicSlugResponses—validateGetTopicSlug200 (200)
topic.getAllTopicsGET /api/topicsAll TopicsGetAllTopicsDataGetAllTopicsResponses—validateGetAllTopics200 (200)
topic.getTopicsGraphGET /api/topics-graph/{topic_slug}Topic GraphGetTopicsGraphDataGetTopicsGraphResponses—validateGetTopicsGraph200 (200)
topic.getRecommendTopicsGET /api/recommend/topics/{ref_list}Recommended TopicsGetRecommendTopicsDataGetRecommendTopicsResponses—validateGetRecommendTopics200 (200)
topic.getRandomByTopicGET /api/texts/random-by-topicRandom By TopicGetRandomByTopicDataGetRandomByTopicResponses—validateGetRandomByTopic200 (200)

term ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
term.getTermsGET /api/terms/{name}TermsGetTermsDataGetTermsResponses—validateGetTerms200 (200)
term.getNameGET /api/name/{name}NameGetNameDataGetNameResponses—validateGetName200 (200)

sheets ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
sheets.getSheetGET /api/sheets/{sheet_id}—GetSheetDataGetSheetResponses—validateGetSheet200 (200)
sheets.getSheetsTrendingTagsGET /api/sheets/trending-tags—GetSheetsTrendingTagsDataGetSheetsTrendingTagsResponses—validateGetSheetsTrendingTags200 (200)
sheets.getSheetModifiedGET /api/sheets/modified/{sheet_id}/{timestamp}—GetSheetModifiedDataGetSheetModifiedResponses—validateGetSheetModified200 (200)
sheets.getUserSheetsGET /api/sheets/user/{user_id}—GetUserSheetsDataGetUserSheetsResponses—validateGetUserSheets200 (200)
sheets.getUserSheetsPaginatedGET /api/sheets/user/{user_id}/{sort_by}/{limiter}/{offset}—GetUserSheetsPaginatedDataGetUserSheetsPaginatedResponses—validateGetUserSheetsPaginated200 (200)
sheets.getSheetsBulkGET /api/v2/sheets/bulk/{sheet_id_list}—GetSheetsBulkDataGetSheetsBulkResponses—validateGetSheetsBulk200 (200)
sheets.getSheetsTagListGET /api/sheets/tag-list—GetSheetsTagListDataGetSheetsTagListResponses—validateGetSheetsTagList200 (200)
sheets.getSheetsTagListSortedGET /api/sheets/tag-list/{sort_by}—GetSheetsTagListSortedDataGetSheetsTagListSortedResponses—validateGetSheetsTagListSorted200 (200)
sheets.getUserSheetTagsGET /api/sheets/tag-list/user/{user_id}—GetUserSheetTagsDataGetUserSheetTagsResponses—validateGetUserSheetTags200 (200)
sheets.getSheetsByRefGET /api/sheets/ref/{ref}—GetSheetsByRefDataGetSheetsByRefResponses—validateGetSheetsByRef200 (200)
sheets.getAllSheetsGET /api/sheets/all-sheets/{limiter}/{offset}—GetAllSheetsDataGetAllSheetsResponses—validateGetAllSheets200 (200)

collections ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
collections.getCollectionsGET /api/collections—GetCollectionsDataGetCollectionsResponses—validateGetCollections200 (200)
collections.getCollectionGET /api/collections/{slug}—GetCollectionDataGetCollectionResponses—validateGetCollection200 (200)
collections.getUserCollectionsGET /api/collections/user-collections/{user_id}—GetUserCollectionsDataGetUserCollectionsResponses—validateGetUserCollections200 (200)

misc ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
misc.postFindRefsPOST /api/find-refsFind RefsPostFindRefsDataPostFindRefsResponses—validatePostFindRefs202 (202)
misc.postSearchWrapperPOST /api/search-wrapperSearchPostSearchWrapperDataPostSearchWrapperResponses—validatePostSearchWrapper200 (200)
misc.getImgGenGET /api/img-gen/{tref}Social Media ImageGetImgGenDataGetImgGenResponses—200: binary body (image/png), no validator
misc.getCategoryGET /api/category/{category_path}CategoryGetCategoryDataGetCategoryResponses—validateGetCategory200 (200)
misc.getProfileGET /api/profile/{slug}—GetProfileDataGetProfileResponses—validateGetProfile200 (200)
misc.getAsyncTaskStatusGET /api/async/{task_id}Get Async Task StatusGetAsyncTaskStatusDataGetAsyncTaskStatusResponsesGetAsyncTaskStatusErrorsvalidateGetAsyncTaskStatus200 (200)
validateGetAsyncTaskStatus202 (202)
validateGetAsyncTaskStatus500 (500)

ref ​

FunctionRequestSummaryOptions typeResponses typeErrors typeValidators
ref.getRefGET /api/ref/{tref}RefGetRefDataGetRefResponsesGetRefErrorsvalidateGetRef200 (200)
validateGetRef404 (404)

Generated types, schemas and validators ​

The package root also exports the generated types, schemas, and validators. This page doesn't list them one by one.

  • Types, such as GetV3TextsData and GetV3TextsResponses, are TypeScript types. The package exports them from the root and from @sefaria/api-client/contracts.
  • Zod schemas have names starting with z, such as zCoreV3TextsResponse. The package exports them from the root and from @sefaria/api-client/schemas.
  • Validators have names such as validateGetV3Texts200, which is the function name plus the status. The package exports them from the root and from @sefaria/api-client/validators.

Reference › Package imports and exports lists every subpath.

Where to go next ​

Sefaria Frontend ToolkitCommunity-driven with Sefaria backing and support. GitHub Get support

AI-generated documentation.

About this documentation

Like the codebase, this documentation was scaffolded and written with GitHub Copilot. I don't have a background in technical writing, and wanted to get something out there.

Pages that have not undergone any human review are explicitly marked, but the others may also read funny or need work too. Sorry about that.

Please report any issues so they can be prioritized.

Thanks, Avi