Typed API contract builder

I've external third party API which doesn't expose any types (no typescript compatible). I would like to be able to define type safe contracts for that API so body, query params, response type etc. is all type safe. Ideally it should be based/wrapped on fetch or implemented with https://github.com/elbywan/wretch or https://github.com/unjs/ofetch. This won't be exposed for anyone. It will be used only internally and only on the backend side so no need for any browser compatibilty. I just want an easy type safe way to define input/outputs and use it from within my express/trpc calls I've found these which resonate a bit with my need but im not sure if there any better ones or should I build something myself. https://ts-rest.com/ https://www.zodios.org/ Any recommendations?
3 Replies
JulieCezar
JulieCezar15mo ago
I don't think you need the last 2 solutions (ts-rest and zodios), because those are meant if you are in control of both the API and the clientside. Since you are talking about a third party API, you will only be sending requests to it and receiving responses from it. I would just recommend using Zod for it, for the query params and needed data you will be sure it will be correct since you will be the one to input the data and for parsing the data received from the api you can just define a type and use zod.safeParse to validate it. Then you can throw an error if the API doesn't return the type you expect... However, this will break the flow of application if you choose to throw an error. So beware and think about your usecase Or you can just log it somewhere that the api has changed or doesn't return expected data, and you can go and fix it from there safeparse example
const result = stringSchema.safeParse("billie");
if (!result.success) {
// handle error then return
result.error;
} else {
// do something
result.data;
}
const result = stringSchema.safeParse("billie");
if (!result.success) {
// handle error then return
result.error;
} else {
// do something
result.data;
}
Gabrola
Gabrola15mo ago
For ts-rest, you can definitely just create a contract for a third-party API and use ts-rest to call that API. No need to be in control of the backend.
JulieCezar
JulieCezar15mo ago
Ok, I've had the wrong impression of what ts-rest was xD After looking through the docs a little better now I would say that it does look like a good solution for it
Want results from more Discord servers?
Add your server