I am a beginner to oatpp and building a crud operation demo application. I want to send only two of these four properties (id, name, email, salary) in dto for change email service, in the request payload like below:
{
"id":"1",
"email":"email1"
}
You can do it by either creating a separate DTO containing these two fields and then assign values,
or by returning oatpp::Fields<oatpp::Any>.
Using oatpp::Any
ENDPOINT("GET", "/", myEndpoint) {
oatpp::Fields<oatpp::Any> responseDto = {
{"id", oatpp::Int32(1)}, //<-- put your id here
{"email", oatpp::String("email1")} //<-- put your email here
};
return createDtoResponse(Status::CODE_200, responseDto);
}
result:
{"id":1,"email":"email1"}
Related
I am new to Ktor and I have a route with a request body which i am parsing with Kotlin Serialization.
I know that the request body is expected to conform to the request body data class but then, I tested by passing the wrong field in my test payload and it crashed the app.
I want to be able to handle such scenarios and respond to the client that such a field is not allowed. How do i go about that.
This is my sample data class:
#kotlinx.serialization.Serializable
data class UserLoginDetails(
var email: String = "",
var password: String = ""
)
This is the route:
post("/user/login") {
val userInfo = call.receive<UserLoginDetails>()
//my code here
}
The payload below works
{
"email": "test#email.com",
"password": "password"
}
But if use an alternative payload for instance:
{
"phone": "test#email.com",
"password": "password"
}
The app crashes with the crash message:
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected
JSON token at offset 7: Encountered an unknown key 'emai'. Use
'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown
keys.
You have two options in Ktor:
call.receive is the function which can throw an exception in this case, you can simply catch it:
try {
val userInfo = call.receive<UserLoginDetails>()
} catch (t: Throwable) {
// handle error
}
Catching exceptions globally using Status Pages:
install(StatusPages) {
exception<SerializationException> { cause ->
call.respond(/* */)
}
}
The error message says you can setup your Json with the config ignoreUnknownKeys = true where you are creating the Json object. Here's the doc link.
a tip: You might also want to check other configuration options so you can avoid setting empty string as default values.
how can I use environment variables for get method in postman, I have customer id's with me but I need to send different customer id's n check the response, but I want to send customer ID's through data driven in postman tool
Imagine there is a customerId in env variables. To send this value in body or as param, just replace the static value with {{customerId}}.
usage:
To update the variable, imagine we have the following response:
{
"success": true,
"data": {
"id": "1234"
}
}
in the test tab update it this way:
var data = JSON.parse(responseBody);
if(data && data.data && data.data.id){
pm.environment.set('customerId', data.data.id)
}
I have request with number of tests cases, same endpoint, different actual values, different expected error messages.
I would like to create parameterized request sending particular value and check particular error message from list with all of the cases.
Request body:
{
"username": "{{username}}",
"password": "{{password}}",
...
}
Response:
{
"error_message": "{{error_message}}",
"error_code": "{{error_code}}"
}
Error message changes due to different cases:
Missed username
Missed password
Incorrect password or username
etc
Now, I have separate request on each case.
Question:
Is there way have 1 request with set of different values, checking
particular error messages/codes?
Create a csv:
username,password,error_message,error_code
username1,password1,errormessage1,errorcode1
username1,password1,errormessage1,errorcode1
Now use this as data file in collection runner or newman.
variable name is same as the column name and, for each iteration you will have corresponding row-column value as the variable value. Eg for iteration1 username will be username1
. As danny mentioned postman has a really rich documentation that you can make use of
https://learning.postman.com/docs/running-collections/working-with-data-files/
Adding another answer on how to run data driven from same request:
Create a environment variable called "csv" and copy the below content and paste it as value:
username,password,error_message,error_code
username1,password1,errormessage1,errorcode1
username1,password1,errormessage1,errorcode1
Now in pr-request add :
if (!pm.variables.get("index")) {
const parse = require('csv-parse/lib/sync')
//Environmental variable where we copy-pasted the csv content
const input = pm.environment.get("csv");
const records = parse(input, {
columns: true,
skip_empty_lines: true
})
pm.variables.set("index", 0)
pm.variables.set("records", records)
}
records = pm.variables.get("records")
index = pm.variables.get("index")
if (index !== records.length) {
for (let i of Object.entries(records[index])) {
pm.variables.set(i[0], i[1])
}
pm.variables.set("index", ++index)
pm.variables.get("index")===records.length?null:postman.setNextRequest(pm.info.requestName)
}
Now you can run data driven for that one particular request:
Eg collection:
https://www.getpostman.com/collections/eb144d613b7becb22482
use the same data as environment variable content , now run the collection using collection runner or newman
Output
I have a query like this in my React/Apollo application:
const APPLICATIONS_QUERY = gql`
{
applications {
id
applicationType {
name
}
customer {
id
isActive
name
shortName
displayTimezone
}
deployments {
id
created
user {
id
username
}
}
baseUrl
customerIdentifier
hostInformation
kibanaUrl
sentryIssues
sentryShortName
serviceClass
updown
updownToken
}
}
`;
The majority of the items in the query are in a database and so the query is quick. But a couple of the items, like sentryIssues and updown rely on external API calls, so they make the duration of the query very long.
I'd like to split the query into the database portion and the external API portion so I can show the applications table immediately and add loading spinners for the two columns that hit an external API... But I can't find a good example of incremental/progressive querying or merging the results of two queries with Apollo.
This is a good example of where the #defer directive would be helpful. You can indicate which fields you want to defer for a given query like this:
const APPLICATIONS_QUERY = gql`
{
applications {
id
applicationType {
name
}
customer #defer {
id
isActive
name
shortName
displayTimezone
}
}
}
`
In this case, the client will make one request but receive 2 responses -- the initial response with all the requested fields sans customer and a second "patch" response with just the customer field that's fired once that resolver is finished. The client does the heavy lifting and pieces these two responses together for you -- there's no additional code necessary.
Please be aware that only nullable fields can be deferred, since the initial value sent with the first response will always be null. As a bonus, react-apollo exposes a loadingState property that you can use to check the loading state for your deferred fields:
<Query query={APPLICATIONS_QUERY}>
{({ loading, error, data, loadingState }) => {
const customerComponent = loadingState.applications.customer
? <CustomerInfo customer={data.applications.customer} />
: <LoadingIndicator />
// ...
}}
</Query>
The only downside is this is an experimental feature, so at the moment you have to install the alpha preview version of both apollo-server and the client libraries to use it.
See the docs for full details.
I am writing a plain post request using spring boot web module, and the fields in my POST request are name, Description and title.
My question is when i use postman or any client to make a POST request to add a new entity, the json keys, name, Description and title are case sensitive, but how can i make the keys case-insensitive. in other words, even when user makes a post request using description instead of Description my application should accept the value and rather not take null since it was not exact match.
Any thoughts are appreciated
You can write function to check your keys are present with case sensitive values or not. In get method you can call method to pick the key.
public String getIgnoreCase(JSONObject obj, String key) {
Iterator<String> itr = obj.keySet().iterator();
while (itr.hasNext()) {
String key1 = itr.next();
if (key1.equalsIgnoreCase(key)) {
return obj.get(key1);
}
}
return null;
}
If u want to keep #RequestBody Item item. then here is solution:
in application.properties:
spring.jackson.mapper.accept_case_insensitive_properties=true
if you use application.yml then:
spring:
jackson:
mapper:
accept_case_insensitive_properties: true