Open API schema conditional response field based on the presence of a query parameter - jsonschema

I am working on providing a GET REST API where I would like to conditionally include the total_documents field (its an integer count of the total number of records present in the DB table).
The API signature and response payload will be something like:
GET /endpoint/?total_documents&.....
Response Payload:
{
documents: [....],
total_documents: 100
}
Now I would like the total_documents field to be appeared in the response payload if and only if the total_documents query parameter exists in the URL.
This is what I tried, based on my schema:
fastify.addSchema({
$id: 'persistence-query-params',
title: "PersistenceQueryParams",
type: 'object',
description: 'Persistence Service GET API URL query specification. Applicable for GET API only.',
properties: {
'total_documents': {
description: 'Total number of documents present in the collection, after applying filters, if any. This query paramater does not take any value, just pass it as the name (e.g. &total_documents).',
nullable: true,
},
},
}
querystring: {
description: 'Persistence Service GET API URL query specification. Applicable for GET API only.',
$ref: 'persistence-query-params#',
},
response: {
200: {
properties: {
'documents': {
description: 'All the retrieved document(s) from the specified collection for the specified service database and account.',
type: 'array',
items: {
$ref: 'persistence-response-doc#',
}
},
'total_documents': {
description: "If total_documents query paremeter is specified, gives the total number of documents present in the collection, after applying query paramaters, if any. If total_documents is not specified, this field will not be available in the response payload.",
type: 'number',
default: -1,
},
},
dependencies: {
'total_documents': { required: ['querystring/properties/total_documents'] },
},
},
'4xx': {
$ref: 'error-response#',
description: 'Error response.'
}
}
What is the way out here?
Thanks,
Pradip

JSON Schema has no notion of a request or response or HTTP.
What you have here is an OpenAPI specification document.
The OpenAPI specification defines a way to access dynamic values, but only within Link Objects or Callback Objects, which includes the query params.
Runtime expressions allow defining values based on information that
will only be available within the HTTP message in an actual API call.
This mechanism is used by Link Objects and Callback Objects.
https://spec.openapis.org/oas/v3.1.0#runtime-expressions
JSON Schem has no way to reference instance data, let alone data relating to contexts it is unaware of.

Related

How to show input and output exemple with nelmio-api-bundle and php8.1

I'm currently trying to make an API doc page thanks to nelmio-api-bundle. I only have one route which is a POST route. I'm receiving a JSON in the body of the request and I'm using the Serializer from symfony to deserialize it in a DTO. I'm also using a DTO for the response (which contains the status code, a bool set to true or false, and a message). Now I'm trying to use these DTO (for input and output) to build the API documentation with nelmio-api-bundle but how to make it ? I'm using PHP8.1 attributes to make it, for response it almost works (except that the response is shows as an array) but I don't know how to make it for the inputs.
Here is my current code:
#[Route('/user', methods: ['POST'])]
#[OA\Parameter(
name: 'user',
description: 'The user information in JSON',
in: 'query',
required: true
)]
#[OA\Response(
response: 200,
description: 'Returns the success response',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: SuccessResponseDTO::class))
)
)]
public function registerUser(Request $request, LoggerInterface $logger): JsonResponse
{
//the code to register the user
}
And here is the result:
Do someone know how to make it ?

How to use Atlassian Document Format in create issue rest api

I am trying to create an issue via Jira API -
{
// other fields is here
description: {
type: "doc",
version: 1,
content: [
{
type: "text",
text: summary
}
}
}
but I get an error - "Operation value must be a string".
so how can I create an issue correctly?
Most likely you're using API version 2 - which accepts text for this field.
However, you're providing value as json (Atlassian Document Format) which is for API version3

RAML : How to require parameter A OR parameter B

I'm writing some REST documentation with RAML but I'm stuck.
My problem:
- I have a GET request used for search that can take a parameter "id" or (exclusive or) "reference". Having only one of them is required.
I know how to say "this param is required" but I don't know how to say "having one of these params is required". Is it even possible?
The following example written in RAML 1.0 defines two object types in Url and File then creates another object Item which requires Url OR File in ext. If you change the included examples (which currently validate), you'll see that they fail if the property does not conform to one or the other definition. Hope that helps! LMK if you have any other questions and I'll do my best.
[EDIT: hmm I think I am seeing your problem now, the final example I've just added, named should_fail, (which has one of each type together in the example) still validates and you want a way to make it fail validation.]
[UPDATE: OK I figured a mildly hacky way to do this. Use maxProperties: 1 in the object which should have properties appear alone, see updated code below which fails the final example during validation.]
#%RAML 1.0
types:
Url:
properties:
url:
type: string
example: http://www.cats.com/kittens.jpg
description: |
The url to ingest.
File:
properties:
filename:
type: string
example: kittens.jpg
description: |
Name of the file that will be uploaded.
Item:
description: |
An example of a allowing multiple types yet requiring
one AND ONLY one of two possible types using RAML 1.0
properties:
ext:
maxProperties: 1
type: File | Url
examples:
file_example:
content:
ext:
filename: video.mp4
url_example:
content:
ext:
url: http://heres.a.url.com/asset.jpg
should_fail:
content:
ext:
url: http://heres.a.url.com/asset.jpg
filename: video.mp4
I had the same problem. User can provide either a textual input OR a file input, but not both.
Both have different fields and I detect the request type from the field names. i.e if the request has [files and parameters], it is a FileInput. If the request has [texts and parameters], it is a TextInput. It is not allowed to provide both text and file within the same request.
I used the union property. See CatAndDog example in
Raml 200 documentation for a small example.
You can define your types as follows.
types:
FileInput:
properties:
parameters:
type: Parameters
description: (...)
files:
type: ArchiveCollection | FileCollection
description: (...)
TextInput:
properties:
parameters:
type: Parameters
description: (...)
texts:
type: TextCollection
description: (...)
Then in my POST request body:
/your_route:
post:
body:
multipart/form-data:
type: TextInput | FileInput
The fields in the body are defined with either TextInput or FileInput type.
In RAML 0.8 you can not describe queryParameters with only one parameter.
In RAML 1.0 you can do this. You should use oneOf in jsonschema for describing Type. Your queryParameters should use this type. Example:
api.raml
#%RAML 1.0
title: AUTH microservice
mediaType: application/json
protocols: [HTTPS]
types:
- example: !include schemas/example.json
/example:
get:
queryParameters:
type: example
schemas/example.json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"id": "file://schemas/credentials.json",
"oneOf": [
{
"properties": {"key1": {"type": "string"}},
"additionalProperties": false
},
{
"properties": {"key2": {"type": "string"}},
"additionalProperties": false
}
]
}
Also you can use uriParameters. Maybe it will help in your case.
#%RAML 0.8
title: API Using media type in the URL
version: v1
/users{mediaTypeExtension}:
uriParameters:
mediaTypeExtension:
enum: [ .json, .xml ]
description: Use .json to specify application/json or .xml to specify text/xml

POST parameters support in RAML

I'd like to ask if there is any support for POST parameters in RAML. And if there is - what is the syntax. I've browsed spec 0.8 and spec 1.0 roughly (actually I'm bound to 0.8, since many tools don't support 1.0 yet). I didn't find POST parameters support, but maybe I just missed something.
So what do I mean by POST parameters? These can be either of the two (sorry, I don't know their formal names, if there are any):
HTTP plain parameters, key=value, each parameter in one line, such as
name=John Doe
amount=5
which is not really handy (e.g. no nesting)
parameters as JSON object, just a JSON with all its syntax allowed (server-side needs to parse this json); such as:
{"name":"John Doe","amount":"5"}
Different server-side API implementations use either 1st or 2nd one. Anyway, how does RAML support these?
As it is shown in this reference https://github.com/raml-org/raml-spec/wiki/Breaking-Changes:
For raml 0.8:
body:
application/x-www-form-urlencoded:
formParameters:
name:
description: name on account
type: string
example: Naruto Uzumaki
gender:
enum: ["male", "female"]
Is the equivalent in raml 1.0 to:
body:
application/x-www-form-urlencoded:
properties:
name:
description: name on account
type: string
example: Naruto Uzumaki
gender:
enum: ["male", "female"]
So what it changes is the formParameters attribute to the properties one.
#Pedro has covered option 2, so here is option 1. Based on the discussion in the comments, it seems the encoding used is application/x-www-form-urlencoded.
You need to use formParameters.
Example:
post:
description: The POST operation adds an object to a specified bucket using HTML forms.
body:
application/x-www-form-urlencoded:
formParameters:
AWSAccessKeyId:
description: The AWS Access Key ID of the owner of the bucket who grants an Anonymous user access for a request that satisfies the set of constraints in the Policy.
type: string
acl:
description: Specifies an Amazon S3 access control list. If an invalid access control list is specified, an error is generated.
type: string
Reference: https://github.com/raml-org/raml-spec/blob/master/raml-0.8.md#web-forms
Post parameters can be expressed using JSON Schema
A simple RAML 0.8 example:
#%RAML 0.8
title: Api
baseUri: /
schemas:
- Invoice: |
{
"$schema": "http://json-schema.org/draft-03/schema",
"type": "object",
"properties": {
"Id": { "type": "integer"},
"Name": { "type": "string"},
"Total": { "type": "number"}
}
}
/invoices:
post:
body:
application/json:
schema: Invoice

Sencha touch 2 - show response (JSON string) on proxy loading

Is there a way to output the json-string read by my store in sencha touch 2?
My store is not reading the records so I'm trying to see where went wrong.
My store is defined as follows:
Ext.define("NotesApp.store.Online", {
extend: "Ext.data.Store",
config: {
model: 'NotesApp.model.Note',
storeId: 'Online',
proxy: {
type: 'jsonp',
url: 'http://xxxxxx.com/qa.php',
reader: {
type: 'json',
rootProperty: 'results'
}
},
autoLoad: false,
listeners: {
load: function() {
console.log("updating");
// Clear proxy from offline store
Ext.getStore('Notes').getProxy().clear();
console.log("updating1");
// Loop through records and fill the offline store
this.each(function(record) {
console.log("updating2");
Ext.getStore('Notes').add(record.data);
});
// Sync the offline store
Ext.getStore('Notes').sync();
console.log("updating3");
// Remove data from online store
this.removeAll();
console.log("updated");
}
},
fields: [
{
name: 'id'
},
{
name: 'dateCreated'
},
{
name: 'question'
},
{
name: 'answer'
},
{
name: 'type'
},
{
name: 'author'
}
]
}
});
you may get all the data returned by the server through the proxy, like this:
store.getProxy().getReader().rawData
You can get all the data (javascript objects) returned by the server through the proxy as lasaro suggests:
store.getProxy().getReader().rawData
To get the JSON string of the raw data (the reader should be a JSON reader) you can do:
Ext.encode(store.getProxy().getReader().rawData)
//or if you don't like 'shorthands':
Ext.JSON.encode(store.getProxy().getReader().rawData)
You can also get it by handling the store load event:
// add this in the store config
listeners: {
load: function(store, records, successful, operation, eOpts) {
operation.getResponse().responseText
}
}
As far as I know, there's no way to explicitly observe your response results if you are using a configured proxy (It's obviously easy if you manually send a Ext.Ajax.request or Ext.JsonP.request).
However, you can still watch your results from your browser's developer tools.
For Google Chrome:
When you start your application and assume that your request is completed. Switch to Network tab. The hightlighted link on the left-side panel is the API url from which I fetched data. And on the right panel, choose Response. The response result will appear there. If you have nothing, it's likely that you've triggered a bad request.
Hope this helps.
Your response json should be in following format in Ajax request
{results:[{"id":"1", "name":"note 1"},{"id":"2", "name":"note 2"},{"id":"3", "name":"note 3"}]}
id and name are properties of your model NOte.
For jsonp,
in your server side, get value from 'callback'. that value contains a name of callback method. Then concat that method name to your result string and write the response.
Then the json string should be in following format
callbackmethod({results:[{"id":"1", "name":"note 1"},{"id":"2", "name":"note 2"},{"id":"3", "name":"note 3"}]});