How it can use datatables/editor with Django rest framework - django-rest-framework

Could someone show me an example code of how I can use datatables/editor with Django rest framework?
My concern is the editor provided some data like this:
{"data": [
{
/*Actual data*/
}],
"action": "create"
}
But Django expects only this, with different Methods (DefaultRouter)
{
/*Actual data*/
}
My first idea was to manipulate by "to_internal_value", but I am not sure it is the best way.
Could someone please help me?

Related

How to create routes configuration itself dynamically

In one of my use case, i have all my route information in a json file and i want to read the file and create the routes accordingly.
for example,
if i have declared route like this in my json config file
{
"config": [
{
"routeSrcSystem": "System1",
"routes": [
{
"fromRoute": {
"type": "default",
"typeValue": "direct:CMStart"
},
"toRoute": {
"type": "http"
"typeMethod": "POST",
"typeContent": "application/json",
"typeValue": "http://localhost:8080/v1/System1/inboundMessage"
}
}
]
}
]
}
then i able to create the routes as below dynamically. but here though its dynamic,the route definition is not dynamic because i have used one "from" and one "to" definition but parameter for this definition i am passing dynamically.
public class GenerateRouter extends RouteBuilder {
private RoutesMetadata routesMetadata;
public GenerateRouter(CamelContext context,RoutesMetadata routesMetadata) {
super(context);
this.routesMetadata=routesMetadata;
}
#Override
public void configure() throws Exception {
from(routesMetadata.getFromRoute().getTypeValue())
.setHeader(Exchange.HTTP_METHOD, simple(routesMetadata.getToRoute().getTypeMethod()))
.setHeader(Exchange.CONTENT_TYPE, constant(routesMetadata.getToRoute().getTypeContent()))
.to(routesMetadata.getToRoute().getTypeValue());
}
}
But i would like to do the route definition itself dynamically. for example, i have route config like this,
{
"config": [
{
"routeSrcSystem": "System1",
"routes": [
{
"fromRoute": {
"type": "default",
"typeValue": "direct:CMStart"
},
"toRoute1": {
"type": "http"
"typeMethod": "POST",
"typeContent": "application/json",
"typeValue": "http://localhost:8080/v1/System1/inboundMessage"
}
"toRoute2": {
"type": "http"
"typeMethod": "POST",
"typeContent": "application/json",
"typeValue": "http://localhost:8080/v1/System2/inboundMessage"
}
}
]
}
]
}
then in my route definition i need to add one more "to" definition dynamically. its just example. it could be more dynamic. for example, configuration can be changed to introduce "process" or "bean" or "class" definition. so based on the config, we need to decide how many "to" to be created and how many "process" to be created and etc. I might need to call the next rest end point after some validation and etc and some times i need to call kafka to put the message in queue. i do see an option to list all routes in a list and execute it but i think we need to have flexibility to add process or to or class definition before we call next end point and this has to be based on configuration.
public class GenerateRouter extends RouteBuilder {
private RoutesMetadata routesMetadata;
public GenerateRouter(CamelContext context,RoutesMetadata routesMetadata) {
super(context);
this.routesMetadata=routesMetadata;
}
#Override
public void configure() throws Exception {
from(routesMetadata.getFromRoute().getTypeValue())
.setHeader(Exchange.HTTP_METHOD, simple(routesMetadata.getToRoute().getTypeMethod()))
.setHeader(Exchange.CONTENT_TYPE, constant(routesMetadata.getToRoute().getTypeContent()))
.to(routesMetadata.getToRoute().getTypeValue())
.setHeader(Exchange.HTTP_METHOD, simple(routesMetadata.getToRoute().getTypeMethod()))
.setHeader(Exchange.CONTENT_TYPE, constant(routesMetadata.getToRoute().getTypeContent()))
.to(routesMetadata.getToRoute().getTypeValue());
}
}
I saw some information where route definition itself can be defined dynamically and i am doing research on it. but meantime i would like to post this here to get experts opinion. Also, please suggest whether I am using the camel on right way? because in my use case i am thinking to add "to" definition to which pass the class name dynamically based on configuration file, so that application developer can do their logic for transformation, enrich or manipulation in this class on the fly before deliver to target system. please let me know if we have any better approach. also, let me know whether XML way of doing is good way or defining own config file in json format is a good way to create dynamic route.
i am planning to read the json file and create a router definition as a string dynamically. but i would need to load this string as a definition in context it seems. i think i am missing this part.
.to("class:com.xxx.camel.layoutTransform?method=layout()")
if we provide all these configurations in xml file and if camel supports to create the route definition automatically using this file then we can consider this option as well.
Below is the one of the way from another source to create the router definition using XML file. within the XML, we have router information defined and this xml considered as a string and this string is converted as router-definition object and finally added into context.
<routes
xmlns=\"http://camel.apache.org/schema/spring\">
<route>
<from uri='direct:c'/>
<to uri='mock:d'/>
</route>
</routes>
CamelContext context = new DefaultCamelContext();
context.setTracing(true);
String xmlString = "<routes xmlns=\"http://camel.apache.org/schema/spring\"><route><from uri='direct:c'/><to uri='mock:d'/></route></routes>";
InputStream is = new ByteArrayInputStream(xmlString.getBytes());
RoutesDefinition routes = context.loadRoutesDefinition(is);
context.addRouteDefinitions(routes.getRoutes());
context.start();
ProducerTemplate template = null;
template = context.createProducerTemplate();
template.start();
template.sendBody("direct:c", "HelloC");
Thread.sleep(10000);
context.stop();
I would like to do the similar concept using java dsl definition as a string.
for example, if i have string as below then can this be converted as a router definition?
String dslString = "from("direct:starting").to("seda:end")";
Here is my use case. Sometime, we want to call 2 http services as below
from("direct:start").to(http://localhost:8080/service1).to("http://localhost:8080/service2")
Somtimes we might need to call 3 services as like below
from("direct:start").to(http://localhost:8080/service1).to("http://localhost:8080/service2").to("http://localhost:8080/service3")
sometimes we need to do transformation before we invoke service2 as like below.
from("direct:start").to(http://localhost:8080/service1).to("class:com.xxx.yyy").to("http://localhost:8080/service2").to("http://localhost:8080/service3")
In the even driven architecture, we will have set of routes must be defined for each event types. so the idea is, if we define these routes in a table for each event type, then at the time of service start up all the routes will be loaded in context and will be started. I am able to do the same in XML DSL way but trying to do the same in java DSL.
Thanks in advance!
Camel supports defining all details about routes in a particular XML-based format. This page has links to that (and other) DSLs.
You could definitely come up with your own DSL and build routes dynamically, but that's a lot of work if you want to support all the things a full Camel DSL would support. I would suspect that is not the right solution for whatever your use-case.
If you have certain patterns to your routes, you can create fairly dynamic Camel route-builders that are driven by some configuration. To make this concrete, let's say you have many use cases that follow a very similar pattern... say, consumer data from files in a folder, do a few transformations from a menu of (say) 10-15 transformations, and then sends output to one of many queues.
Since you have various possible combinations, it could make sense to configure those details in file etc. and then build some routes off that. The trade-off is not different from any other place where you have to decide if it is clearer to just code the 10 things you want, or to make something more complex but generic.
Essentially, you would still be creating a DSL or sorts, but one that is closer to your use case.

Apollo GraphQL mutation signature equivalent to PUT

I'm trying to effectively do a PUT request with GraphQL
Mutation:
export const UPDATE_CAT = gql`
mutation updateCat($catRef: RefInput, $payload: CatInput) {
updateCat(ref: $catRef, input: $payload) {
${ref}
}
}
`;
Query variables:
{
"catRef": {
"id": "7b342789-e527-42a6-997b-cfe2fb6bdb07",
"typename": "cat.beacon.Beacon"
},
"payload":{
"position": null,
}
}
Although this seems to wipe all of the props on the cat entity (it does not delete the resource). Is this the correct syntax for a PUT like request?
First of all, I think it's worth to note that graphql is protocol agnostic. That means any transport protocol can be used, not necessarily HTTP (despite HTTP is used in most cases).
Also, what do you mean by PUT like request? As I understand, you state that HTTP PUT method is used to patch data. Which might not be true. It depends on how you implement this. You can easily create a REST API that is accepting data via GET and sending via POST or PUT method despite this is not recommended by best practices.
The same situation here with your problem. It's not about your mutation signature, it's about mutation resolver implementation.
In order to make this work, you should determine in your resolver function on a server if this is a new or existing resource and handle both scenarios properly.
How can you check if this is a new resource? Id prop will be undefined in this case, right?
If you are working with third-party api then check it's docs.

Communicating acceptable string values in Swagger docs

Spring Boot (Java) here. Does Swagger have any customizable/configurable fields that allows you to specify specific String values that an endpoint either accepts or returns?
For instance I might have an endpoint like so:
POST /v1/{accountId}/preferences
{
"notificationTypes" : [
]
}
...that accepts an array of notificationTypes in its request entity. Perhaps my server only allows AdminNotification and SimpleAlert as the possible values for this notificationTypes, meaning:
POST /v1/{accountId}/preferences
{
"notificationTypes" : [
"SimpleAlert"
]
}
is valid but:
POST /v1/{accountId}/preferences
{
"notificationTypes" : [
"Hello"
]
}
throws a 400 Bad Request. I'd like to be able to communicate this in my Swagger docs. Is this configuration possible via annotations?
I think a good solution would be to create an ENUM with the accepted values. This way, it will be automatically described in Swagger:
#ApiModelProperty(value= "Accepted values are :")
public NotificationTypes notificationTypes;
public enum NotificationTypes {SimpleAlerts, AdminNotifications}
In the generated specifications, it gives the following:
Have fun !
You can use something like -
notificationTypes:
type: string
example: ["SimpleAlert", "otherValue"]
look - https://gyazo.com/1c8774fbf08410c19df0506a52a767d6
ref - https://swagger.io/docs/specification/adding-examples/

Laravel 5.5 Rest Api

I am creating a Laravel Application that supports mobile app and normal blade.
my Big problem of how to differentiate between return view and return json
there is a lot of opinion of how to organize the code I'd like to know what is the best practice for my case.
1- Create Different Controllers 1 for web other for mobile ( kills DRY concept )
2- Create 1 Controller for mobile return json and call it's functions from the web controller
3- Create service class contains the logic and create 2 controllers and inject an object in the constructore EX : [ Services/UserService.php ] [ UserController.php ] [ Api/UserController.php ]
which way should i Follow
Thanks in advance.
You can keep the code logic in the same controller#method and use wantsJson to determine Accept header and build an appropriate response
// build $responseData
if (Request::wantsJson()) {
return response()->json($responseData);
}
else {
return view('view')->with($responseData);
}

spring data rest hal browser: how to expose resource descriptions and document

I have looked all over the net, trolled through spring-data-rest source code and tried to decipher how the JS for the hal-browser is trying to retrieve 'title' and 'doc' details for a resource. I have also discovered that there are
#RepositoryRestResource(
collectionResourceRel = "roles",
path = "roles",
itemResourceDescription = #Description("This is a test description")
)
Annotations I can put in the #Repostitory, but it doesn't seem to do anything.
Specifically, if you look at this example, how do I get "title|doc" to fill in"
I filed a ticket with spring and haven't heard back.
From what I can see the HAL Browser expects the link to contain the title property. In the example you linked:
{
"motd": "Welcome to the OSDI Example Action Platform OSDI API endpoint!!",
"_links": {
"osdi:people": {
"href": "http://api.opensupporter.org/api/v1/people",
"title": "The collection of people in the system"
}
...
}
The org.springframework.hateoas.Link class does not support that property as of version 0.19.0.RELEASE. No idea about the docs though...

Resources