There is a nifty concept called Lambda authorizers, where access to an API can be controlled by using either a Cognito user Pool or a lambda function.
For an API protected by Cognito User Pool Authorizers, a token passed in a request header of choice is validated against a pool of tokens issued by Cognito.
For an API protected by a Lambda authorizer, a token passed in the request header or a query parameter or a stage context is passed to a lambda function that's executed when the aforementioned request is received by the API gateway. The token-validation logic contained in the lambda can be as complex and flexible as desired.
The official documentation describes it in more detail.