how to send null field in object body with ktor - ktor

I want to send null field in body of a request with ktor.
I use kotlinx.serialization library and use #Required annotation in top of that null filed. but ktor remove null fileds from request body!! how can I fix this?

Related

can not send int to respond in ktor

I'm trying to send int response but get an error but when I use both as a string then response get successfully.
post("/employee") {
call.respond(mapOf("hey" to "Hey","if" to 1))
}
LOGCAT
java.lang.IllegalStateException: Serializing collections of different element types is not yet supported. Selected serializers: [kotlin.String, kotlin.Int]
at io.ktor.serialization.kotlinx.SerializerLookupKt.elementSerializer(SerializerLookup.kt:45)
at io.ktor.serialization.kotlinx.SerializerLookupKt.guessSerializer(SerializerLookup.kt:29)
at io.ktor.serialization.kotlinx.KotlinxSerializationBase.serialize$ktor_serialization_kotlinx(KotlinxSerializationBase.kt:34)
at
You can't pass different types in response "yet" like mentioned in stacktrace. As a workaround you can pass 1 as string or create custom class for this response and serialize it to json and send it like that

Ktor returns 415 from endpoints where receive() is used with ContentNegotiation

I have parameter classes with the #Searializable annotation:
#Serializable
data class ShowPostURL(
val date: String,
val titleSlug: String,
override val redirectTo: String? = null
)
and no matter what I do call.receive() won't work. I'm getting HTTP 415 errors and Ktor doesn't log anything. I've added the serialization support as well:
install(ContentNegotiation) {
json()
}
How do I fix this? This is how I'm trying to use it:
accept(ContentType.Any) {
get("/foo/{date}/{titleSlug}") {
val input = call.receive(ShowPostURL::class)
call.respondText("foo")
}
}
If I do a trace I can see that my route is matched, but it can't receive the parameters. Is this json() setup is supposed to work when I'm deserializing from url parameters like this?
Firstly, ContentNegotiation feature works only for receiving custom objects from the payload of POST, PUT and PATCH requests:
POST, PUT and PATCH requests have an associated request body (the payload). That payload is usually encoded.
In order to receive custom objects from the payload, you have to use the ContentNegotiation feature. This is useful for example to receive and send JSON payloads in REST APIs.
When receiving, the Content-Type of the request will be used to determine which ContentConverter will be used to process that request
Secondly, there are three out of the box ContentConverter available:
GsonConverter, JacksonConverter and SerializationConverter.
Each of these converters has its own configuration function: gson, jackson and serialization respectively. You use json configuration function which is most likely is not appropriate for the configuration of ContentNegotiation.
To solve your problem you can access URL parameters by referring them with call.parameters and manually create ShowPostURL object. Then serialize it with the kotlinx.serialization framework if needed.
Also, you can write your own ContentConverter to implement custom logic for receiving typed objects.

Validating API response in Karate framework [duplicate]

This question already has answers here:
Can we parameterize the request file name to the Read method in Karate?
(2 answers)
Closed 1 year ago.
I want help for validating API response using karate framework.
I have API’s which are “Independent” on each other.
I have POST method along with request parameters. when I hit that particular API got the response with different parameters (no single match from request parameter and response parameter).
Now I want to validate response parameter value.
example : request: “method” post
school name: “abcd”
register date : “1:10:2010″
Response:
Principle name : ” pqrs”
Principle Email id “pqrs#gmail.com
now I want to validate that “principle name ” should not be null
I have implemented like this but it it doesn’t work
Feature: School info
Background:
* url baseUrl
Scenario: check Principles info
Given path ‘School info’
And request {school name: “abcd” ,register date : “1:10:2010”}
When method post
Then status 200
And match response.response contains {“type”: “Success”,”code”:20000}
And match response.principle list[*] { “Principle name”: “#notnull”}
whenever I run this file it always passes the API wvwnt if the Principle name filed is null.
It just checks the success message (And match response.response contains {“type”: “Success”, ”code”:20000}) and pass the API
your code for validating principlelist doesn't have proper assertions.
match each will be more convenient for validating json array with a schema
* match each response.principlelist contains {"Principal name" : "#notnull"}

Apache Camel : How to setHeader value as null

How do we set header value as null in apache camel exchange message from a processor. I am delivering message to a RabbitMQ exchange and it expects one of the header value to be set as null.
I have tried below approaches from my processor just before delivering the message
exchange.getOut().setHeader("headername","");
But this sets up an empty string to the header.
I also tried
exchange.getOut().setHeader("headername",null);
But in this case the header itself is not visible.
Please let me know if any more information is needed.
The camel-rabbitmq component does not support headers with null values. They are filtered out in the source code.
https://github.com/apache/camel/blob/fab7a58e56e128286f327aba16c09553b26cb846/components/camel-rabbitmq/src/main/java/org/apache/camel/component/rabbitmq/RabbitMQMessageConverter.java#L171
Its a odd requirement/use-case to have to send a null value. And hence why I ask you to explain this more. There must be very good reason to consider changing Camel.
Camel has implemented a fix for this which is backported to the 2.22.1 and 2.21.3 versions and will be available there onwards. For those who are interested to know how this can be achieved, please have a look at Camel-12654 Jira issue.
camel-rabbitmq component and endpoint now support a URI option allowNullHeaders which is false by default. If you want to send custom headers with value as null, set its value to true. For example
from("rabbitmq://hostname:port/exchangeName?allowNullHeaders=true").....
This will configure camel-rabbitmq converter to set headers with null values. Now from your processor, you can do something like this
exchange.getOut().setHeader("headername",null);
This will instruct camel-rabbitmq producer, not to skip and headers which have null values.

Unable to add body to RestSharp RestRequest using enums

I am using RestSharp in ASP .NET MVC 2 project. Trying to create RestRequest (using POST method) and add two enum values (my enum type -- OrderStatusFlags) to request body -- using build-in RestSharp XmlSerializer:
var request = new RestRequest("orders/{vendorID}/{number}", Method.POST);
request.AddBody(previousOrderStatus);
request.AddBody(newOrderStatus);
But after calling AddBody method in request parameters can see only empty but no value. And while calling MVC action method an error occurs:
The parameters dictionary contains a null entry for parameter 'previousStatus' of non-nullable type 'OrderStatusFlags' for method 'RestResponse PostOrderStatus(Int32, System.String, OrderStatusFlags, OrderStatusFlags)' in 'OrdersResourceEndpoint'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Enum look like this:
public enum OrderStatusFlags : long
{
Pending,
Confirmed,
...
}
Does anybody occurs a similiar situation?
A couple issues here. First, you can only call AddBody() once or the last call will take precedence. AddBody() is also only for sending XML as the request body. What is the required XML schema that you need to send to that URL? Can you post some sample XML that you're trying to generate?
I think more likely you actually want to use AddParameter() to add some POST parameters since that is far more common than XML request bodies.