Type System

API Star comes with a type system that allows you to express constraints on the expected inputs and outputs of your interface.

The Type class

Here’s a quick example of what the type system in API Star looks like:

from apistar import types, validators


class Product(types.Type):
    name = validators.String(max_length=100)
    rating = validators.Integer(minimum=1, maximum=5)
    in_stock = validators.Boolean(default=False)
    size = validators.String(enum=['small', 'medium', 'large'])

You can use the type system both for validation of incoming request data, and for serializing outgoing response data.

Invalid data will result in a ValidationError being raised.

>>> data = {'name': 't-shirt', 'size': 'big'}
>>> product = Product(data)
apistar.exceptions.ValidationError: {'rating': 'This field is required.', 'size': 'Must be a valid choice.'}

Valid data will instantiate a new Type instance.

>>> data = {'name': 't-shirt', 'rating': 4, 'size': 'large'}
>>> product = Product(data)
<Product(name='t-shirt', rating=4, in_stock=False, size='large')>

You can access the values on a Type instance as attributes.

>>> product.name
't-shirt'

Or treat a Type as a dictionary-like object.

>>> product['rating']:
4
>>> dict(product)
{'name': 't-shirt', 'rating': 4, 'in_stock': False, 'size': 'large'}

Nested types

You can include Type classes as fields on other Type classes, like so:

class Location(types.Type):
    latitude = validators.Number(maximum=90.0, minimum=-90.0)
    longitude = validators.Number(maximum=180.0, minimum=-180.0)


class Event(types.Type):
    location = Location
    name = validators.String(max_length=100)

API Reference

The following typesystem types are supported:

String

Validates string data.

Number

Validates numeric data.

Integer

Validates integer data.

Boolean

Validates boolean input.

Object

Validates dictionary input.

You'll typically want to use the simpler declarative Type style for describing dictionary inputs, but the Object validator may be useful if you need more general purpose validation.

Array

Validates list input.

Formats

The following validators return a native python representation, but can be serialized to strings.

Let's declare a new type to see how they work...

from apistar import types, validators


class Event(types.Type):
    when = validators.DateTime()
    description = validators.String(max_length=100)

When accessed as attributes on a type, these validators return the native python value.

>>> data = {'when': '2021-06-15T12:31:38.269545', 'description': 'New customer signup'}
>>> event = Event(data)
>>> event.when
datetime.datetime(2021, 6, 15, 12, 31, 38, 269545)

You can also access the serialized string representation if needed.

>>> event['when']
'2021-04-11T12:31:38.269545'
>>> dict(event)
{'when': '2021-04-11T12:31:38.269545', 'description': 'New customer signup'}

Date

Time

DateTime