Serve JSON from an OpenAPI contract
A client asks the Journal for JSON. What should the action return? We’ll start with the response in the OpenAPI file and construct a value of that shape in Bend.
Pick the response in Bend
Find the status code and content type you want to return in the operation. Bwf generates a Bend constructor for that response. Use it in your action and the compiler will check the value you put inside.
Import the JSON schema
Start with a local OpenAPI 3.0.x or 3.1.x file. Give the fields the names you want clients to see in JSON. The decoder looks for those names on input and the encoder writes them on output. The build can follow supported references to definitions in local files.
type: object
additionalProperties: false
required: [title]
properties:
title: {type: string}
archived: {type: boolean}Read the body and return a response
Try leaving out the boolean in this object. It’s optional. Leave out the title instead and the decoder rejects the request. It also checks that the title is a string. On the way out, pick the generated response constructor for the status and content type your action is returning.
The Journal puts the article list directly into its generated response constructor.
Api.Articles200{articles}Tell a missing key from JSON null
For an update, you may want a missing subtitle to mean ‘leave it alone’ and an explicit null to mean ‘clear it.’
An optional nullable field can carry all three cases. Supported decimal codecs can preserve the decimal representation, and enum encoders keep the values named in the public schema.
Each line below is a separate request body.
{}
{"subtitle": null}
{"subtitle": "Field notes"}Publish the contract you imported
Call Api.document_json() to return the same document the app imported. External references, multipart uploads and overlapping untagged object unions are outside the supported subset. A schema format like email gives you a string. Apply the app’s email rules where you use it.
With the Journal running, request the generated contract.
curl -fsS http://127.0.0.1:18088/docs/openapi.json