haskell-servant / haskell-servant/servant

Define API with newtypes

Open
#1,094 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Haskell
Stars
2k
Forks
427
Avg merge
2d 23h
Merged PRs (30d)
5

Description

Hello,
I use newtypes in my API, for body and URL parts (for security). Is there examples/documentation on that?
I'm not sure which instances I need.
For example, I came up with:
```
newtype Foo = Foo Text deriving (Show, Eq, Generic)

instance ToSchema Foo where
declareNamedSchema proxy = genericDeclareNamedSchema defaultSchemaOptions proxy
& mapped.schema.example ?~ toJSON ("MyFoo" :: Text)
`
instance ToParamSchema Foo

instance ToJSON Foo where
toJSON = genericToJSON (defaultOptions {AT.unwrapUnaryRecords = True})

instance FromJSON Foo where
parseJSON = genericParseJSON (defaultOptions {AT.unwrapUnaryRecords = True})

instance FromHttpApiData Foo where
parseUrlPiece a = Right $ Foo a

instance ToHttpApiData Foo where
toUrlPiece (Foo a) = a

newtype Bar = Bar Text deriving (Show, Eq, Generic)

type FooAPI =
Capture "foo_id" FooId :> Get '[JSON] Bar
:<|> ReqBody '[PlainText] Bar :> PutNoContent '[JSON] NoContent
```

This freezes when I invoke PUT with a string body.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.