How to handle submitted array of json with fosrest bundle and nemio api doc bundle - symfony

I have a controller in my Rest API that expects an array of json (in POST)
{
data: [
{
name: "marc"
},
{
name: "john"
}
]
}
Submitted data are then saved in database.
I don't know what annotation to use in order to tell "nelmio api doc bundle" to generate the appropriate html page in order to have capability to test my API by creating multiple items (an array of items).
To resume the question is : Can nelmio documentation generates a dynamic collection of forms ?

You can test your API through nelmio sandbox.
Nelmio have the "New Parameter" button which is can add multiple key => value parameters.

Related

How to create api with resource not based on entity API Platform?

I need to create a GET endpoint to return a resource which is fetched from another application via http client, not based on entity. The resource I fetched is an array:
[
"id" => 1234
"first_name" => ""
"last_name" => ""
"email" => ""
"country" => 1
"country_code" => 93
"phone_number" => "3434343"
"nationality" => "AF"
"professional_industry" => "Health Care"
"job_title" => "Medical Doctor - General Practitioner"
"specialisation" => "No specialisation"
"career_length_month" => 1
"career_length_year" => 1
]
Then I need to query database to fetch some data to add to the resource array.
So I created it in src/Controller/MyController.php:
/**
* #Route("/api/v1/get-profile", name="get_profile")
* #return JsonResponse
*/
public function getMemberInfo(): JsonResponse
{
// step 1 : use http client to request data from another application
// step 2 : query DB to fetch some data and add to data array
return new JsonResponse($data, Response::HTTP_OK);
}
But now, I would like my api return json api response format : https://jsonapi.org/.
With resource based on entity, it is supported completely by api-platform. I don't need to do much. I just adding "key" #[ApiResource] in entity class and config some things. Then I have a api with json api format, so easily:
{
"data": {
"id": "",
"type": "",
"attributes": {}
}
}
But how about with resource not based on Entity? Is there any built-in feature of api-platform I could use, or I have to do a transformer by myself ?
You need override the OpenAPI specification how described in documentation:
https://api-platform.com/docs/core/openapi/#overriding-the-openapi-specification
Then, in the new class, you must add the schema definition that you require, adding new PathItem instances, each PathItem require new Operation instances, etc.
Sorry for not paste examples, it require so many code. I'm working this way in a project, but it's not public for now.
I hope I put you in the way.
The good practice is to can create a custom data provider. This custom data provider will be responsible to fetch data from the external source. Then, API-Platform will be able to use it like a regular entity.
Documentation
Full example in the API-Platform demo

firebase auth token from Graphcool

can I generate a custom auth token, for use with a third party, with a resolver in graph.cool? something like this??
type FirebaseTokenPayload {
token: String!
}
extend type Query {
FirebaseToken(userIdentifier: String!): FirebaseTokenPayload
}
const fb = require('myNodeFirebaseAuthLib')
module.exports = event => fb.generateTokenWithPayload({ id: event.data.userId })
Authentication required - restrict who can read data in fields: Permission query:
query ($user_id: ID!, $node_firebaseIdentifier: String) {
SomeUserExists(filter: {
id: $user_id ,
firebaseIdentifier: $node_firebaseIdentifier
})
}
--
I think this question boils down two parts
"is it possible to install node modules in the graph.cool instance -- or for that sort of thing do we need to use a webhook" -- if it must be a webhook, what is the flow of identity verification and how do I pass the payload parameters ?
"can we add permissions queries and authentication to resolvers?"
notes, addendums:
according to this alligator.io blog post, it seems that using the Graphcool framework, you can install node modules! So, I wouldn't need to use a webhook. -- However, that is with an ejected app. I lose auth0 authentication that way -- the template does not produce a createUser and singinUser that works with the same auth0 data that the integration offers.
I forgot to post the answer to this - I had to eject graphcool, I could not use any node_modules I thought to try in my custom functions.

Simple GetItem with ctx.identity.username returns null

I'm using AppSync with IAM auth with a DynamoDB resolver and Cognito. I'm trying to do the following.
{
"version": "2017-02-28",
"operation": "GetItem",
"key": {
"userId": $util.dynamodb.toDynamoDBJson($ctx.identity.username)
}
}
$ctx.identity.username is supposed to contain userId generated by Cognito and I'm trying to use it to fetch current user data.
Client side, I'm using AWS Amplify that tells me I'm currently logged:
this.amplifyService.authStateChange$.subscribe(authState => {
if (authState.state === 'signedIn') {
this.getUserLogged().toPromise();
this._isAuthenticated.next(true);
}
});
getUserLogged is the Apollo query that is supposed to returns user data.
What I've tried:
If I leave it like this, getUserLogged returns null.
If I replace in the resolver $util.dynamodb.toDynamoDBJson($ctx.identity.username) with a known userId like this $util.dynamodb.toDynamoDBJson("b1ad0902-2b70-4abd-9acf-e85b62d06fa8"): It works! I get this user data.
I tried to use the test tool in the resolver page but it only gives fake data so I can't rely on this.
Did I make a mistake? To me everything looks good but I guess I'm missing something?
Can I clearly see what $ctx.identity contains?
You'll want to use $ctx.identity.cognitoIdentityId to identify Cognito IAM users:
https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference.html#aws-appsync-resolver-context-reference-identity
You could see the contents of $ctx.identity by creating a Lambda resolver and logging the event or by creating a local resolver and returning the input that the mapping template receives:
https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-local-resolvers.html
My cognitoIdentityId looks like this: eu-west-1:27ca1e79-a238-4085-9099-9f1570cd5fcf

Is routes case-sensitive in Web API OData Service using ODataController?

i followed this to learn how ODataController works, everything is OK but when i changed the request uri
from
"localhost:49292/odata/Employees" //result: 200
to
"localhost:49292/odata/employees" //result: 404
to say one word: "odata" or "Odata" and "Employee" are all ok, but lowercase "employee" return 404. any explanation about this. Moreover, the routes in asp.net mvc is not case-sensitive afaik.
how about including a Route attribute and direct it to lower case. for Upper case web api will take care about it
[Route("odata/employees")]
add this on the top of the controller
if odata is common for every action then you can include [RoutePrefix] attribute
You can manually do it using the ODataModelBuilder instead of the ODataConventionModelBuilder
e.g
var builder = new ODataModelBuilder();
builder.EntitySet<Order>("Employees");
builder.EntitySet<Order>("employees");
this will work but your metadata will show 2 entity sets:
{
#odata.context: "http://localhost:62881/$metadata",
value: [
{
name: "Employees",
kind: "EntitySet",
url: "Employees"
},
{
name: "employees",
kind: "EntitySet",
url: "employees"
}
]
}
lowercase "employee" return 404.
I hope you probably didn't have the typo like that.
AFAIK, there is a case limitation on filter and properties. (You can vote there https://aspnetwebstack.codeplex.com/workitem/366 ) but not sure about the controller name..
You can create the REST server using web api without having oData as well..

Extjs 4 - Retrieve data in json format and load a Store. It sends OPTION request

I'm developing an app with Spring MVC and the view in extjs 4. At this point, i have to create a Grid which shows a list of users.
In my Spring MVC controller i have a Get method which returns the list of users in a jsonformat with "items" as a root.
#RequestMapping(method=RequestMethod.GET, value="/getUsers")
public #ResponseBody Users getUsersInJSON(){
Users users = new Users();
users.setItems(userService.getUsers());
return users;
}
If i try to access it with the browser i can see the jsondata correctly.
{"items":[{"username":"name1",".....
But my problem is relative to request of the Ext.data.Store
My Script is the following:
Ext.onReady(function(){
Ext.define('UsersList', {
extend: 'Ext.data.Model',
fields: [
{name:'username', type:'string'},
{name:'firstname', type:'string'}
]
});
var store = Ext.create('Ext.data.Store', {
storeId: 'users',
model: 'UsersList',
autoLoad: 'true',
proxy: {
type: 'ajax',
url : 'http://localhost:8080/MyApp/getUsers.html',
reader: {type: 'json', root: 'items'}
}
});
Ext.create('Ext.grid.Panel',{
store :store,
id : 'user',
title: 'Users',
columns : [
{header : 'Username', dataIndex : 'username'},
{header : 'Firstname', dataIndex: 'firstname'}
],
height :300,
width: 400,
renderTo:'center'
});
});
When the store tries to retrieve the data and launchs the http request, in my firebug console appears OPTIONS getUsers.html while the request in the browser launchs GET getUsers.html
As a result, Ext.data.Store has not elements and the grid appears with the columnames but without data. Maybe i've missed something
Thank you
You can change the HTTP methods that are used by the proxy for the different CRUD operations using actionMethods.
But, as you can see in the doc (and as should obviously be the case), GET is the default for read operations. So the OPTIONS request you are observing is quite puzzling. Are you sure that there's not another part of your code that overrides the default application-wide? Maybe do a search for 'OPTIONS' in all your project's JS files, to try and find a possible suspect. Apparently there's no match in the whole Ext code, so that probably doesn't come from the framework.
Edit:
Ok, I think I've got it. If your page is not accessed from the same domain (i.e. localhost:8080, the port is taken into account), the XHR object seems to resort to an OPTIONS request.
So, to fix your problem, either omit the domain name completely, using:
url: '/MyApp/getUsers.html'
Or double check that your using the same domain and port to access the page and make the requests.

Resources