Magento 2 API Create Order As guest: {"message":"\"%fieldName\" is required. Enter and try again.","parameters":{"fieldName":"email"}} - json

I'm trying to place an order via Magento 2 API as a guest, following the guidance shown here:
https://devdocs.magento.com/guides/v2.4/rest/tutorials/orders/order-create-order.html
The end point I'm using is:
https://[domain]/rest/V1/guest-carts/'.$quote_id.'/payment-information
with quote_id being the ID of the quote created initially
Steps 1-6 complete successfully with relevant response being returned as expected.
But sending the following payload (literally a copy and paste from the docs) to the above endpoint:
{
"paymentMethod": {
"method": "banktransfer"
},
"billing_address": {
"email": "jdoe#example.com",
"region": "New York",
"region_id": 43,
"region_code": "NY",
"country_id": "US",
"street": [
"123 Oak Ave"
],
"postcode": "10577",
"city": "Purchase",
"telephone": "512-555-1111",
"firstname": "Jane",
"lastname": "Doe"
}
}
Results in this error message:
{"message":""%fieldName" is required. Enter and try again.","parameters":{"fieldName":"email"}}
The email address IS obviously being supplied, and am really at a loss as to what's going wrong.
For info, the API this is being sent to is a vanilla install of Magento set up with a test product for testing purposes
Does anyone have any ideas, or at least some suggestions as to how I can debug given the not very usefulness of the error message given?

You are Sending POST Request so you also have to send data in POST request in json format like :{ ""id"": {}}
And have to set Content-Type:application/json in http header.

Related

Check if partial string in JSON values in Python

I'm trying to check if a value contains a partial string in this sample API call result in JSON format. It should look through job title text to see if it contains the word "Virtual" or "Remote" anywhere in the string. If so, append 1 to new dictionary, and if not, append 0. I keep getting 1's for each value, but not sure why 0's don't show up if it can't find any match. Thanks! Here's the code:
import requests
remote_job_check = {'Remote':[]}
job_lists = {
"jobs": [
{
"country_code": "US",
"state": "AL",
"title": "Sr. Customer Solutions Manager - Virtual Opportunities",
},
{
"country_code": "US",
"state": "CA",
"title": "Data Engineer",
},
{
"country_code": "US",
"state": "CA",
"title": "Data Engineer - Remote",
},
{
"country_code": "US",
"state": "NV",
"title": "Remote Software Engineer",
},
{
"country_code": "US",
"state": "FL",
"title": "Product Manager",
}
]
}
job_data = requests.get(job_lists).json()['jobs']
for details in job_data:
if 'Virtual' or 'Remote' in details.get('title'):
remote_job_check['Remote'].append(1)
else:
remote_job_check['Remote'].append(0)
I was able to figure it out. Thanks for the suggestions though. I learned that my original code only searches for one of the strings. The 'or' operator wasn't even working in this case:
for details in job_data:
if 'Virtual' or 'Remote' in details.get('title'): # The 'or' operator not working
remote_job_check['Remote'].append(1)
else:
remote_job_check['Remote'].append(0)
Then I tried using just one string and it worked.
for details in job_data:
if 'Virtual' in details.get('title'): # This works
remote_job_check['Remote'].append(1)
else:
remote_job_check['Remote'].append(0)
So now I figured I need to create some sort of array to iterate through and found the 'any' function. Here's the working code:
remote_job_keywords = ['Virtual', 'Remote']
if any(keyword in details['title'] for keyword in remote_job_keywords):
job_data['Remote'].append(1)
else:
job_data['Remote'].append(0)
UPDATE: Thanks to #shriakhilc for the feedback on my answer. Like he said, the above works but it was easier to fix the or operator like so:
for details in job_data:
if 'Virtual' in details.get('title') or 'Remote' in details.get('title'):
remote_job_check['Remote'].append(1)
else:
remote_job_check['Remote'].append(0)

Should I sent images through JSON

I'm new to Django, and I'm building a REST backend for my iOS app, I figured out encode an Image to it's Base64 data, and I would like to use it together with some texts, is it a good idea to put it into the JSON for the rest of the data or is it better to use another request to download each image data.
I'm guessing that separating concerns is the best way, and have two GET request to retrieve the data, but I just want to be sure!.
OPTION A
{
"owner": {
"username": "lilysmith",
"email": "lily#email.com",
"first_name": "Lily",
"last_name": "Smith"
},
"is_user_page": true,
"title": "Lily Smith",
"subtitle": "Photographer",
"about": [
{
"icon": "🇺🇸",
"label": "Austin, TX"
}
],
"photos": [
{
"position": 2,
"description": "I love hiking",
"photo": "/9j/2wCEAAgGBg....CEAAgGBg" <- (The rest of the binary data)
}
]
}
OPTION B (Separating Concern)
The same JSON response, but instead of image data, using it's id.
Then getting it just the data through another request, but esencially making the front end handle two or more request to server.

Search parameter not working with the API request

I am new to json and APIs.
This particular dataset I am working with (https://api.cdnjs.com/libraries) is searchable by placing ?search=search_term after it (like: https://api.cdnjs.com/libraries?search=cloud). But when I use another json dataset (http://api.nobelprize.org/v1/prize.json for instance) it gives an error:
{ "error":"Using an unknown parameter" }
Does this have to do with how the datasets are set up? Methods perhaps? How do I make the other json searchable like the initial one (so I can use it in my search app)?
Navigating to the main domain of the provided url, you will find that the doc reside at https://nobelprize.readme.io/v1.0
To refine your results, as the docs suggest you should use the following parameters (when searching for prizes): year, yearTo, category and numberOfLaureates.
Here is an example of a refined search:
Request url: http://api.nobelprize.org/v1/prize.json?category=physics&year=2017
Response:
{
"prizes": [{
"year": "2017",
"category": "physics",
"laureates": [{
"id": "941",
"firstname": "Rainer",
"surname": "Weiss",
"motivation": "\"for decisive contributions to the LIGO detector and the observation of gravitational waves\"",
"share": "2"
}, {
"id": "942",
"firstname": "Barry C.",
"surname": "Barish",
"motivation": "\"for decisive contributions to the LIGO detector and the observation of gravitational waves\"",
"share": "4"
}, {
"id": "943",
"firstname": "Kip S.",
"surname": "Thorne",
"motivation": "\"for decisive contributions to the LIGO detector and the observation of gravitational waves\"",
"share": "4"
}]
}]
}
If it wasn't clear enough, I made a request to the API to retrieve data concerning prizes awarded in the physics category in the year 2017.

Grails 3.1.8 : Spring Rest Docs using Rest Assured giving PayloadHandlingException: com.fasterxml.jackson.databind.JsonMappingException

I'm trying to implement ascii doc with snippet for grails rest-api with rest-assured for json response :
{
"instanceList": [
{
"firstName": "Coy",
"lastName": "T",
"pictureUrl": null,
"email": "bootstrap#cc.com",
"bio": null,
"skills": [],
"interestAreas": []
},
{
"firstName": "Jane",
"lastName": "D",
"pictureUrl": null,
"email": "jane#cc.com",
"bio": null,
"skills": [],
"interestAreas": []
},
{
"firstName": "Cause",
"lastName": "C",
"pictureUrl": "https://cc-picture.com",
"email": "cc-user#code.com",
"bio": "cc beyond infinity",
"skills": [],
"interestAreas": []
},
{
"firstName": "sachidanand",
"lastName": "v",
"pictureUrl": null,
"email": "cc#cc.com",
"bio": null,
"skills": [],
"interestAreas": []
}
],
"totalCount": 4
}
and the code snippet of UserDocumentationApiSpec(as IntegrationTest) :
void 'test and document get request for /user'() {
expect:
given(documentationSpec)
.header("AuthToken", "TokenValue")
.accept(MediaType.APPLICATION_JSON.toString())
.filter(document('user-list-v1',
preprocessRequest(modifyUris()
.host('127.0.0.1')
.removePort()),
preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("[].firstName").description("First name of user"),
fieldWithPath("[].lastName").description("Last name of user"),
fieldWithPath("[].pictureUrl").type(JsonFieldType.STRING).description("Picture Url of user"),
fieldWithPath("[].email").description("Email address of user"),
fieldWithPath("[].bio").description("Bio data of user"),
fieldWithPath("totalCount").description("Count of instanceList field"),
fieldWithPath("type").description("Type of result")
))).
when()
.port(8080)
.get('/api/v1/user')
.then()
.assertThat()
.statusCode(is(200))
}
This part of code giving me error trace as :
org.springframework.restdocs.payload.PayloadHandlingException: com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
at [Source: [B#2c6adbe3; line: 1, column: 1]
at org.springframework.restdocs.payload.JsonContentHandler.readContent(JsonContentHandler.java:84)
at org.springframework.restdocs.payload.JsonContentHandler.findMissingFields(JsonContentHandler.java:50)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:113)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:74)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:64)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:192)
at org.springframework.restdocs.restassured.RestDocumentationFilter.filter(RestDocumentationFilter.java:63)
at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
at com.jayway.restassured.filter.session.SessionFilter.filter(SessionFilter.java:60)
at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
at org.springframework.restdocs.restassured.RestAssuredRestDocumentationConfigurer.filter(RestAssuredRestDocumentationConfigurer.java:65)
at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
at com.jayway.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:1574)
at com.jayway.restassured.internal.RequestSpecificationImpl.get(RequestSpecificationImpl.groovy:159)
at com.converge.docs.UserApiDocumentationSpec.$tt__$spock_feature_0_0(UserApiDocumentationSpec.groovy:73)
at com.converge.docs.UserApiDocumentationSpec.test and document get request for /user_closure2(UserApiDocumentationSpec.groovy)
at groovy.lang.Closure.call(Closure.java:426)
at groovy.lang.Closure.call(Closure.java:442)
at grails.transaction.GrailsTransactionTemplate$1.doInTransaction(GrailsTransactionTemplate.groovy:70)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at grails.transaction.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:67)
at com.converge.docs.UserApiDocumentationSpec.test and document get request for /user(UserApiDocumentationSpec.groovy)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
at [Source: [B#2c6adbe3; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3781)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3721)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2819)
at org.springframework.restdocs.payload.JsonContentHandler.readContent(JsonContentHandler.java:81)
... 21 more
Please correct me where I'm going wrong...
The only reason I see for this failing is that you are not getting the expected response from the /api/v1/user endpoint.
Follow these steps:
Check that instances are there in the database.
Check that you are sending the correct token.
Write a test case using the RestBuilder and see if you actually get the expected response.
Your code and JSON looks fine.
Also, make sure you follow this issue and mark your empty array field as optional and explicitly provide a type for its contents.
I hope this helps.
I frequently see the error: org.springframework.restdocs.payload.PayloadHandlingException: com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
When there is no response. I see this is a get request. These integration tests work a little bit differently in Grails than RestClient. Have you setup a sample data point in this test or in the bootstrap.Groovy file? I can't see the rest of the code see how you are running this as an integration test. In my sample Grails example, I setup some test data in the Bootstrap.groovy file.
Please let me know if I can help.

Which is the right approach to validate a mandatory field in front end or back end?

I am new in back end development. I have already write the API to update user info, whose request body like this -
{
"id": 26,
"email": "tom.richards#yahoo.com",
"firstName": "Tommy",
"lastName": "Richards",
"photoUrl": null,
"userAddress": [
{
"id": 8,
"type": "home",
"addressLine1": "DP Road",
"addressLine2": "Main Street",
"city": "Los Angel",
"state": "CA",
"country": "USA",
"postalCode":915890
},
{
"id": 25,
"type": "office",
"addressLine1": "Dr Red Road",
"addressLine2": null,
"city": "SA",
"state": "CA",
"country": "USA",
"postalCode":918950
}
]
}
Where should ideally validate the address type [in my case home or office] in front end[Web site or Phone] or back end [server side] or both side? Which is good approach to validate address type ? If we validate it on backend side, which will cause any performance issue ?
Note -
If the developer pass any string, the address type of like pass string will create in DB.
It's a good approach for the back end validate everything it gets from any web request, as you can't tell if its a good request coming from your web site or some other source (maybe even some malicious attack). The back-end must protect itself and validates everything it gets.
On top of it, on some (if not all) cases it's good to do some validations on the front end side too, one reason is that if you have a request that you know the back end is going to fail- save yourself the trouble and check it before you do an expensive request
Reasons
Front End Validation : Validation on the server, User has to wait for the response in case of the invalid data.
Backend Validation : To make sure that the data could not alter by the intruder.
Validate #database end : Like Mongoose provide the built in and custom validation.
As per the requirement we have to cross check the data before user profile update.