API Model Defintions

Viewed 53

Typically when I am making API calls I am using javascript (ajax). JSON doesn't include value types of properties, and so everything is passed as a string.

Since I manage my own API I create request-able models that will tell you the definition of a model.

For example Id value type is int, StartDate value type is date.

I use the property types to automate form creation.

Is there a standard as to how to do this? My way works, but I'd prefer to be doing this by the book if it already exists.

2 Answers

OpenAPI is a standard you could follow. If you also make use of Swagger, it will allow you to produce a JSON schema which can be used in generating forms.

The hard part is typings are done at compilation and JS does that in browser.

You could use a typing model agent such as graphQL that adds a definition for those types ahead of time. Those definitions can then be dynamically fetched and enforced using typescript and a tool like apollo.

If you dont want to use typescript or graphql you could use something like mongoose schema and expose the schema on an endpoint then have your front end rebuild the schema dynamically to check types by casting when creating new objects.

Personally ive done this old fashion way by writing my own form schema and enforce the form types strictly on the front end by interpreting the fieldTypes

// returned from API somewhere
const fields = [{
   type: 'input',
   name: 'firstName'
   rank: 0,
   validation: '/^[a-zA-Z\s]+$/'
}]

Edit: Found this great library that exports typed interfaces based on graphQL models. https://github.com/avantcredit/gql2ts

Related