Generic output schema with one variable difference - swagger

Quick question, im working with swagger-php to annotate my API. The output of the API always has the same basic structure and is being used over several endpoints:
[
{
"status": "success",
"count": 0,
"schema": "Hash.Hash",
"items": [
{ ... },
{ ... },
**LIST OF ITEMS IN THE schema Hash.Hash**
],
"log": [
"string"
]
}
]
My solution for this is using an output model and reference that in the reposonse:
/**
* #OA\Schema(schema="OutputModel",
* #OA\Property( property="status", default="success", type="string", format="string" ),
* #OA\Property( property="count", default=0, type="integer", format="int32" ),
* #OA\Property( property="schema", default="Hash.Hash", type="string", format="schema" ),
* #OA\Property( property="items", type="array", #OA\Items(ref="#/components/schemas/Hash.Hash")),
* #OA\Property( property="log", type="array", #OA\Items(type="string") ),
* )
*/
/**
* #OA\Get(
* path="/api/v1/hash/",
* #OA\Response(response="200", description="List of added hashes",
* #OA\JsonContent(#OA\Items(ref="#/components/schemas/OutputTest")),
* )
* )
*/
My challenge here is that in the output model, the property items is not always of schema Hash.Hash but different for every output. My current solution is to make a new output model for every endpoint and just change the ref="#/components/schemas/Hash.Hash" for the right schema, but this does not look very efficient. Is there a way to make this work using one generic OutputModel, different endpoints with different schemas?

After a lot of reading/tinkering i found the best solution for me:
replaced:
#OA\Property(
property="items", type="array",
#OA\Items(ref="#/components/schemas/Hash.Hash")
)
for:
#OA\Property( property="items", description="TODO", type="array",
#OA\Items(anyOf={
#OA\Schema(ref="#/components/schemas/Hash.Hash"),
#OA\Schema(ref="#/components/schemas/Show.ShowsFollow"),
...etc etc...
}))
And replaced:
#OA\Property( property="schema", default="Hash.Hash", type="string", format="schema" ),
for:
#OA\Property(
property="schema", default="",
type="string", format="schema",
enum={"Hash.Hash", "Show.Showsfollow", ... etc,etc ...}
)
This definition works for me because the schema string defines the object type and the items is filled with that object.
Ties.

Related

Replace "id" parameter with custom parameter in openapi_context (Swagger) - api-platform

I have my custom operation for an entity, it uses PUT method, i ould like to document the parameter in my swagger (OpenApi) documentation.
This is the definition
/*
* itemOperations={
* "get",
* "patch",
* "put",
* "delete",
* "activate"={
* "method"="PUT",
* "path"="/user/{token}/activate",
* "requirements"={"token"="^\w{32}$"},
* "controller"=ActivateUser::class,
* "normalization_context"={"groups"={"user:read"}},
* "denormalization_context"={"groups"={"user:activation"}},
* "read"=false,
* "validation_groups"={"Activate"},
* "openapi_context"={
* "summary"="Attiva un utente tramite token dopo la registrazione.",
* "description"="Cambia lo stato dell'utente in 'attivo' permettendo così il login.",
* "parameters"={
* {
* "in"="path",
* "name"="token",
* "required"=true,
* "type"="string",
* "description"="Il token generato al momento della registrazione."
* }
* }
* }
* },
* },
*/
The part interested is the "openapi_context" key then "parameters".
This description doesn't change anything about parameters definitions, the ID requirement still remains and there's no token description (i read the documentation here for path parameters in open api context
Where am i wrong? Is there a way to do it?

Why am I receiving random null field values on my influx queries?

I have a production application in which I am using a nodejs client to query the last point of a measurement every second. A separate client is writing a point to the measurement on a 1 second interval as well. After a few minutes, I occasionally start receiving null values for random fields. Some fields have data and others are null.
If I re-query for that exact same point a second later, all the values are there. I have also outputted the data to a csv file, and all the data is there as well.
I have recreated the issue on a standalone example. The issue occurs no matter if I use the npm influx library or make the http requests myself. The more frequent the requests are sent, the more frequent I get points containing null values. With the below example, if I run several instances of this app simultaneously, then many points will contain null values.
Is it possible that I am reading the point before influx has written all field values?
Any help is appreciated.
I'm using influx v 1.8.2 and have recreated the issue on ubuntu and windows.
Code to recreate:
const { InfluxDB } = require("influx");
const influx = new InfluxDB({
host: "localhost",
database: "testDb",
});
const createDb = async () => {
await influx.createDatabase("testDb");
};
const read = async () => {
const res = await influx.query(`
select * from livedata
ORDER BY time desc
limit 1
`);
console.log(res[0]);
};
const write = async () => {
await influx.writeMeasurement("livedata", [
{
tags: {
id: "site",
},
fields: {
site1: Math.random() * 1000,
site2: Math.random() * 1000,
site3: Math.random() * 1000,
site4: Math.random() * 1000,
site5: Math.random() * 1000,
site6: Math.random() * 1000,
site7: Math.random() * 1000,
site8: Math.random() * 1000,
},
},
]);
};
createDb();
setInterval(() => {
write();
read();
}, 300);
Example output:
[
'2021-01-07T21:40:11.4031559Z',
'site',
830.4042230769617,
522.1830877694142,
698.8789904008146,
678.305459618109,
118.82269436309988,
631.6295948279627,
376.3112870744887,
830.4872612882643
]
]
[
[
'2021-01-07T21:40:11.7034901Z',
'site',
null,
null,
null,
65.3968316403697,
680.7946463560837,
330.7338852317838,
872.7936919556367,
145.03057994702618
]
]
[
[
'2021-01-07T21:40:12.0036893Z',
'site',
901.031149970251,
501.1825877093237,
99.38758592260699,
78.79549874505165,
403.8558500935323,
545.085784401504,
969.637642068842,
51.657735620841194
]
]

How to generate Model/Example value section for GET request in Swagger

I am concerned on generating Model/Example value section for my GET request with Swagger.
The link to official example shows that section perfectly.
In official docs it is generated using existing model:
* #SWG\Schema(ref="#/definitions/User")
I don't have such an option, because my properties is generated by REST.
I have tried the following way:
/**
* #SWG\Get(
...
* #SWG\Response(
* response="200",
* description="Ok",
* #SWG\Schema(
* type="array",
* #SWG\Property(property="firstname", type="string", example="Steven")
* ),
* ),
* )
*/
It is not working and answers:
fetching resource list: http://localhost/dist/swagger.json; Please wait.
Any help is highly appreciated. Thanks in advance.
The GET /pet/findByStatus is generated in one of the examples:
github.com/zircote/swagger-php/.../Examples/petstore.swagger.io/controllers/PetController.php
The reason your snippet isn't working is because you're adding a property to an array type, which isn't supported.
To describe the contents of the array you'll need the #SWG\Items annotation:
...
* #SWG\Schema(
* type="array",
* #SWG\Items(
* type="object",
* #SWG\Property(property="firstname", type="string", example="Steven")
* )
* ),
...

ZendDeveloperTools not working with ZfcRbac

I installed ZfcRbac instead of BjyAuthorize. Toolbar of ZendDeveloperTools is partially working. I cannot find a reason for the following warning. What is missing in my setup ?
Warning: Invalid argument supplied for foreach() in C:\dev\xampp\htdocs\OnlineFieldEvaluation\vendor\zf-commons\zfc-rbac\view\zend-developer-tools\toolbar\zfc-rbac.phtml on line 94
Notice: Undefined index: guards in C:\dev\xampp\htdocs\OnlineFieldEvaluation\vendor\zf-commons\zfc-rbac\view\zend-developer-tools\toolbar\zfc-rbac.phtml on line 38
Guest role
( ! ) Notice: Undefined index: options in C:\dev\xampp\htdocs\OnlineFieldEvaluation\vendor\zf-commons\zfc-rbac\view\zend-developer-tools\toolbar\zfc-rbac.phtml on line 19
EDIT 1:
This part of my changes related to ZfcRbac which broke ZendDeveloperTools:
zfc_rbac.global.php
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
use ZfcRbac\Guard\GuardInterface;
/**
* Copy-paste this file to your config/autoload folder (don't forget to remove the .dist extension!)
*/
return [
'zfc_rbac' => [
/**
* Key that is used to fetch the identity provider
*
* Please note that when an identity is found, it MUST implements the ZfcRbac\Identity\IdentityProviderInterface
* interface, otherwise it will throw an exception.
*/
'identity_provider' => 'ZfcRbac\Identity\AuthenticationIdentityProvider',
// 'identity_provider' => 'Application\Entity\Systemuser',
/**
* Set the guest role
*
* This role is used by the authorization service when the authentication service returns no identity
*/
'guest_role' => 'guest',
/**
* Set the guards
*
* You must comply with the various options of guards. The format must be of the following format:
*
* 'guards' => [
* 'ZfcRbac\Guard\RouteGuard' => [
* // options
* ]
* ]
*/
// 'guards' => [],
'guards' => [
'ZfcRbac\Guard\RouteGuard' => [
'zfcuser/login' => ['guest'],
'zfcuser' => ['guest'],
'home' => ['student'],
],
],
/**
* As soon as one rule for either route or controller is specified, a guard will be automatically
* created and will start to hook into the MVC loop.
*
* If the protection policy is set to DENY, then any route/controller will be denied by
* default UNLESS it is explicitly added as a rule. On the other hand, if it is set to ALLOW, then
* not specified route/controller will be implicitly approved.
*
* DENY is the most secure way, but it is more work for the developer
*/
'protection_policy' => \ZfcRbac\Guard\GuardInterface::POLICY_DENY,
/**
* Configuration for role provider
*
* It must be an array that contains configuration for the role provider. The provider config
* must follow the following format:
*
* 'ZfcRbac\Role\InMemoryRoleProvider' => [
* 'role1' => [
* 'children' => ['children1', 'children2'], // OPTIONAL
* 'permissions' => ['edit', 'read'] // OPTIONAL
* ]
* ]
*
* Supported options depend of the role provider, so please refer to the official documentation
*/
// 'role_provider' => [],
'role_provider' => [
'ZfcRbac\Role\ObjectRepositoryRoleProvider' => [
'object_manager' => 'doctrine.entitymanager.orm_default', // alias for doctrine ObjectManager
'class_name' => 'Application\Entity\MyHierarchicalRole',
'role_name_property' => 'name'
],
],
/**
* Configure the unauthorized strategy. It is used to render a template whenever a user is unauthorized
*/
'unauthorized_strategy' => [
/**
* Set the template name to render
*/
'template' => 'error/no-auth'
],
/**
* Configure the redirect strategy. It is used to redirect the user to another route when a user is
* unauthorized
*/
'redirect_strategy' => [
/**
* Enable redirection when the user is connected
*/
'redirect_when_connected' => true,
/**
* Set the route to redirect when user is connected (of course, it must exist!)
*/
'redirect_to_route_connected' => 'zfcuser',
/**
* Set the route to redirect when user is disconnected (of course, it must exist!)
*/
'redirect_to_route_disconnected' => 'zfcuser/login',
/**
* If a user is unauthorized and redirected to another route (login, for instance), should we
* append the previous URI (the one that was unauthorized) in the query params?
*/
'append_previous_uri' => true,
/**
* If append_previous_uri option is set to true, this option set the query key to use when
* the previous uri is appended
*/
'previous_uri_query_key' => 'redirectTo'
],
/**
* Various plugin managers for guards and role providers. Each of them must follow a common
* plugin manager config format, and can be used to create your custom objects
*/
// 'guard_manager' => [],
// 'role_provider_manager' => []
]
];
This my zdt.local.php :
<?php
return array(
'zenddevelopertools' => array(
/**
* General Profiler settings
*/
'profiler' => array(
/**
* Enables or disables the profiler.
*
* Expects: bool
* Default: true
*/
'enabled' => true,
/**
* Enables or disables the strict mode. If the strict mode is
* enabled, any error will throw an exception, otherwise all
* errors will be added to the report (and shown in the toolbar).
*
* Expects: bool
* Default: true
*/
'strict' => true,
/**
* If enabled, the profiler tries to flush the content before the it
* starts collecting data. This option will be ignored if the Toolbar
* is enabled.
*
* Note: The flush listener listens to the MvcEvent::EVENT_FINISH event
* with a priority of -9400. You have to disable this function if
* you wish to modify the output with a lower priority.
*
* Expects: bool
* Default: false
*/
'flush_early' => false,
/**
* The cache directory is used in the version check and for every storage
* type that writes to the disk.
*
* Note: The default value assumes that the current working directory is the
* application root.
*
* Expects: string
* Default: 'data/cache'
*/
'cache_dir' => 'data/cache',
/**
* If a matches is defined, the profiler will be disabled if the
* request does not match the pattern.
*
* Example: 'matcher' => array('ip' => '127.0.0.1')
* OR
* 'matcher' => array('url' => array('path' => '/admin')
*
* Note: The matcher is not implemented yet!
*/
'matcher' => array(),
/**
* Contains a list with all collector the profiler should run.
* Zend Developer Tools ships with 'db' (Zend\Db), 'time', 'event', 'memory',
* 'exception', 'request' and 'mail' (Zend\Mail). If you wish to disable a default
* collector, simply set the value to null or false.
*
* Example: 'collectors' => array('db' => null)
*
* Expects: array
*/
'collectors' => array(),
),
/**
* General Toolbar settings
*/
'toolbar' => array(
/**
* Enables or disables the Toolbar.
*
* Expects: bool
* Default: false
*/
'enabled' => true,
/**
* If enabled, every empty collector will be hidden.
*
* Expects: bool
* Default: false
*/
'auto_hide' => false,
/**
* The Toolbar position.
*
* Expects: string ('bottom' or 'top')
* Default: bottom
*/
'position' => 'bottom',
/**
* If enabled, the Toolbar will check if your current Zend Framework version
* is up-to-date.
*
* Note: The check will only occur once every hour.
*
* Expects: bool
* Default: false
*/
'version_check' => false,
/**
* Contains a list with all collector toolbar templates. The name
* of the array key must be same as the name of the collector.
* *
* Example: 'profiler' => array(
* 'collectors' => array(
* // My_Collector_Example::getName() -> mycollector
* 'MyCollector' => 'My_Collector_Example',
* )
* ),
* 'toolbar' => array(
* 'entries' => array(
* 'mycollector' => 'example/toolbar/my-collector',
* )
* ),
*
* Expects: array
*/
'entries' => array(),
),
),
);
This issue has started after this commit:
https://github.com/zendframework/ZendDeveloperTools/commit/d3432681aa32177a741ad23604a40af9ad454acb
However, there are a fix waiting to be merge:
https://github.com/ZF-Commons/zfc-rbac/pull/297
In the same pull request there are a temporary fix:
I don't think this has been fixed yet, so as a temporary solution I
have made the following changes: In
./module/Application/config/module.config.php:
'view_manager' => array( 'template_map' => array(
// Temp fix until this is approved: https://github.com/ZF-Commons/zfc-rbac/pull/296
'zend-developer-tools/toolbar/zfc-rbac' => __DIR__ . '/../view/zend-developer-tools/toolbar/zfc-rbac.phtml', ), ),
Then copy the zfc-rbac.phtml file from the ./vendor directory into
./module/Application/view/zend-developer-tools/toolbar (note:
'Application' in the application.config.php must be loaded after
'ZfcRbac')
In the newly created zfc-rbac.phtml , modify the top few lines to look
like this:
$this->collector->unserialize($this->collector->serialize()); /* #var
$collection \ZfcRbac\Collector\RbacCollector */ $collection =
$this->collector->getCollection();

How to correctly annotate this function for swagger?

I am trying to write a little Api using Slim. I want to have it documented very well so I installed swagger-php and UI and investigated on it the last days. For some reason my petstore demo is missing all the post annotations. My API will look like in this example:
http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/
How would the swagger annotations for the addWine() function look like?
How do I annotate the result of the function (last insert id), since it is no model ?
An example would be really great.
Thank you
This would do it. Propably not ment to be like this, but doing exactly what I wanted.
/**
* #package
* #category
* #subpackage
*
* #SWG\Resource(
* apiVersion="1.0.0",
* swaggerVersion="1.2",
* basePath="http://myapi",
* resourcePath="/hello",
* description="Giving you your name in case you forgot it",
* produces="['application/json','application/xml','text/plain','text/html']"
* )
*/
/**
* #SWG\Api(
* path="/hello/{yourname}",
* #SWG\Operation(
* method="GET",
* summary="Gives you your name",
* notes="Returns your name",
* type="hello",
* nickname="yourname",
* #SWG\Parameter(
* name="yourname",
* description="Enter your name",
* required=true,
* type="text",
* paramType="path"
* ),
* #SWG\ResponseMessage(code=404, message="Bad, really bad name.")
* )
* )
*
*/
/**
* #package
* #category
* #subpackage
*
* #SWG\Model(id="hello",required="name")
*/
/**
* #SWG\Property(name="name",type="string",description="Your name")
*/

Resources