I´m trying to send a POST request that is an Person
object that contains a list of contacts.
But I don´t know if this is the correct syntax to send a list:
{
"name":"romulo",
"contacts" : [
{
"contact" : "3466577"
},
{
"contact" : "532423"
}
]
}
But keeps me returning a 404 error
what i´m doing wrong?
post method:
@PostMapping("/person")
public void addPerson(@Valid @RequestBody Person person) {
Person savedPerson = personRepository.save(person);
List<Contact> contacts = person.getContacts();
for (Contact contact1 : contacts) {
contactRepository.save(contact1);
}
}
asked Feb 25, 2018 at 3:05
Rômulo SoratoRômulo Sorato
1,5605 gold badges17 silver badges29 bronze badges
5
HTTP 404 is returned when the server is unable to find method to match your exact request.
For the mentioned request have the url as http://<context>/requestpath
with request method as POST.(http://localhost:8080/person
)
Check the request body and all the fields should exactly match the Person object else it may return HTPP 400.
answered Feb 25, 2018 at 6:13
1
In My Case it was simple mistake and spend an hour for figuring it out that i had space at the end of my url.
answered Sep 17, 2021 at 7:16
1
I have updated the POSTMAN to the latest version. When I hit the Update option I get ‘You are up to date! Postman v6.0.10 is the latest version.’
I have been successful to send a POST from my another POSTMAN and able to get the correct response. However, I have been running into an issue when sending a POST method to the same API from my POSTMAN. Does not seem to be a routing issue, as it works with another client.
Is it related to any configuration problem or any setting that I need to configure from POSTMAN end?
Been struct into this for some time now, with no clue. Any helps would be greatly appreciated!
Following is the curl command:
curl -X GET
http://SERVER/endpoint/endpoint/ID/endpoint
-H ‘Authorization: bearer ‘
-H ‘Cache-Control: no-cache’
-H ‘Content-Type: application/....***+json’ OR application/json
-H ‘Postman-Token: ac11bb07-3v4f-411b-a712-g6f8c6a74781’
-d ‘{
«user»: «user1»,
«description»: «Test Action»,
«mandatory»: true
}’
I am currently working on a small personal project(springboot + MYSQL), in that while testing in POSTMAN , its showing 404 resource not found .
NOTE: both application and MYSQL is running successfully without any problem and POSTMAN is working properly.
controller is fine as of my knowledge.
where is the problem in code? kindly help me out.
Main class
@SpringBootApplication
public class CafeManagementSystemApplication {
public static void main(String[] args) {
SpringApplication.run(CafeManagementSystemApplication.class, args);
}
}
controller
INTERFACE :
@RequestMapping(path = "/user")
public interface UserRest {
@PostMapping(path = "/signup")
public ResponseEntity<String> signup(@RequestBody(required = true) Map<String,String> requestMap);
}
CLASS:
@RestController
@RequestMapping(path = "/user")
public class UserRestImpl implements UserRest {
@Autowired
UserService userService;
@PostMapping(path = "/signup")
public ResponseEntity<String> signup(Map<String, String> requestMap) {
// TODO Auto-generated method stub
try {
return userService.signUp(requestMap);
} catch (Exception e) {
e.printStackTrace();
}
return CafeUtils.getResponseEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Service
@Service
@Slf4j
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao; // repository
@Override
public ResponseEntity<String> signUp(Map<String, String> requestMap) {
try {
log.info("{Inside signUp {}",requestMap);
if(validateSignupMap(requestMap)) { // method present in same class
User user=userDao.findByEmailId(requestMap.get("email"));
if(Objects.isNull(user)) {
userDao.save(getUserFromMap(requestMap));
return CafeUtils.getResponseEntity("Successfully registered ", HttpStatus.OK);
}
else {
return CafeUtils.getResponseEntity("email already present",HttpStatus.BAD_REQUEST);
}
}
else {
return CafeUtils.getResponseEntity(CafeConstants.INVALID_DATA, HttpStatus.BAD_REQUEST);
}
}
catch(Exception e) {
e.printStackTrace();
}
return CafeUtils.getResponseEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR);
}
private Boolean validateSignupMap(Map<String,String> requestMap) {
if(requestMap.containsKey("name") && requestMap.containsKey("contactNumber") && requestMap.containsKey("email") && requestMap.containsKey("password"))
{
return true;
}
return false;
}
private User getUserFromMap(Map<String,String> map) { // MAP to USER object
User u= new User();
u.setName(map.get("name"));
u.setContactNumber(map.get("contactNumber"));
u.setEmail(map.get("email"));
u.setPassword(map.get("password"));
u.setStatus("false");
u.setRole("user");
return u;
}
}
POJO
@NamedQuery(name="User.findByEmailId", query = "select u from User u where u.email=:email")
@Entity
@Table(name="user")
@DynamicInsert
@DynamicUpdate
@Data
public class User implements Serializable{
private static final long serialVersionUID=1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
@Column(name = "conatactNumber")
private String contactNumber;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@Column(name = "status")
private String status;
@Column(name = "role")
private String role;
}
**REPO **
public interface UserDao extends JpaRepository<User, Integer> {
User findByEmailId(@Param("email") String email);
}
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/cafe?allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=password_root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.format_sql=true
server.port=8081
POM.XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.inn.cafe</groupId>
<artifactId>com.inn.cafe</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Cafe Management System</name>
<description>Cafe Management System Project </description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
I tried to test in POSTMAN ,but its showing 404 error .
NOTE: postman is working properly ,i have checked by testing another application.
what the problem in the code ? where to look out for in the application
when i hit http://localhost:8081/user/signup , i am getting 404
- Remove From My Forums
-
Question
-
User-539691603 posted
I created a Post method and when i go to run this method on the Postman, it doesn’t work.
Controller:
[Route("api/[controller]")]
public class OptOutClientController : Controller
{
private IOptOutCreateService optOutCreateService;
HttpClient httpClient = new HttpClient();
public OptOutClientController(IOptOutCreateService optOutCreateService)
{
this.optOutCreateService = optOutCreateService;
}
[HttpPost]
public async Task<IActionResult> OptOutPostClient([FromBody]OptOutRequest client)
{
if (client == null)
throw new OptOutException( "Favor informar os dados do OptOut!");
var result = await optOutCreateService.Process(new OptOutCreateCommand(client.Cpf, client.Email, client.Telefone, client.Bandeira, client.Canal));
return Ok(new ApiReturnItem<OptOutResult> { Item = result, Success = true });
}
}
How can i put a screenshot here? I’m not getting to do this.
Answers
-
User475983607 posted
pnet
I wrote this code(i’m writting). I’m starting to write this code, then i have nothing, only one controller and some class.
As I explained several time now.. Echo back the input to verify you’ve correctly formatted the request.
namespace CoreApi.Controllers { [Route("api/[controller]")] [ApiController] public class HomeController : Controller { [HttpPost] public int Postar([FromBody]int teste) { return teste; } } }
PostMan Url: https://localhost:44394/api/Home
Body: 1
Note the body does NOT contain {«teste» : 1}.
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User753101303 posted
pnet
Error 404: http://localhost:55522/api/optoutclient/optoutpostclient
As explained the url is wrong and should not include the action name. You shouldn’t have this any more now.
pnet
Error 500: http://localhost:55522/api/optoutclient
As explained it means you have a server side exception. If you still have this problem you should start from the exact exception message you have (client is likely null but it’s best to always start from an actual error message rather than trying to guess
from the code).-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
Solution 1
HTTP 404 is returned when the server is unable to find method to match your exact request.
For the mentioned request have the url as http://<context>/requestpath
with request method as POST.(http://localhost:8080/person
)
Check the request body and all the fields should exactly match the Person object else it may return HTPP 400.
Solution 2
In My Case it was simple mistake and spend an hour for figuring it out that i had space at the end of my url.
Comments
-
I´m trying to send a POST request that is an
Person
object that contains a list of contacts.
But I don´t know if this is the correct syntax to send a list:{ "name":"romulo", "contacts" : [ { "contact" : "3466577" }, { "contact" : "532423" } ] }
But keeps me returning a 404 error
what i´m doing wrong?
post method:
@PostMapping("/person") public void addPerson(@Valid @RequestBody Person person) { Person savedPerson = personRepository.save(person); List<Contact> contacts = person.getContacts(); for (Contact contact1 : contacts) { contactRepository.save(contact1); } }
-
Hi there,thanks for the answer.The correct url is :localhost:8080/api/person because of the base url mapping @RestController @RequestMapping(«/api») public class ContactController. i tried to put all the fields but is still not working: { «personId»: 1 «name»:»romulo», «contacts» : [ { «id»:1 «contact» : «3466577» }, { «contact» : «532423» } ] }
-
In my case, I had a space at the end of my endpoint url and I had removed that in Postman :V