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);
}
}
Vy Do
46.9k60 gold badges215 silver badges318 bronze badges
asked Feb 25, 2018 at 3:05
Rômulo SoratoRômulo Sorato
1,5705 gold badges18 silver badges29 bronze badges
5
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
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
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);
}
}
Vy Do
46.9k60 gold badges215 silver badges318 bronze badges
asked Feb 25, 2018 at 3:05
Rômulo SoratoRômulo Sorato
1,5705 gold badges18 silver badges29 bronze badges
5
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
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
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
Ваш запрос на выполнение запроса с использованием Postman к Restful endpoint, и получение ошибки 404, является распространенной проблемой, с которой многие программисты сталкиваются. В этой статье мы рассмотрим возможные причины ошибки 404 при использовании Postman, и как ее можно решить.
Прежде всего, давайте разберемся в том, что такое ошибка 404. Код состояния HTTP 404 Not Found указывает, что запрашиваемый ресурс не найден на сервере. В контексте выполнения запроса с использованием Postman, это означает, что ваш запрос не может найти конечную точку API, которую вы пытаетесь вызвать.
Есть несколько возможных причин, по которым вы можете получить ошибку 404 при выполнении запроса с использованием Postman. Давайте рассмотрим их по одной и попробуем найти решения для каждой проблемы:
1. Неправильно набранная конечная точка:
Возможно, вы неправильно ввели конечную точку вашего API в Postman. Убедитесь, что вы правильно указали путь к вашей конечной точке, включая любые параметры и подпути.
2. Неправильная настройка метода запроса:
Убедитесь, что вы правильно настроили тип запроса в Postman. Например, если вашей конечной точке требуется GET-запрос, убедитесь, что вы выбрали правильный метод запроса в Postman.
3. Ошибка в спецификации API:
Иногда ошибка 404 может быть вызвана ошибками или недостаточностью в документации или спецификации вашего API. Убедитесь, что вы правильно читаете и понимаете документацию, и что ваш запрос соответствует требованиям API.
4. Отключенный или недоступный сервер API:
Возможно, ваш сервер API временно недоступен или отключен. Попробуйте повторить свой запрос позже, чтобы убедиться, что проблема не связана с недоступностью сервера.
5. Аутентификация или авторизация:
Если ваше API требует аутентификации или авторизации, проверьте, правильно ли вы настроили эти параметры в Postman. Убедитесь, что вы используете правильные токены или ключи доступа.
6. Ошибка в вашем коде:
Возможно, ошибка 404 вызвана ошибкой в вашем собственном коде. Проверьте свой код и убедитесь, что вы правильно обрабатываете запросы и ответы в соответствии с требованиями вашего API.
Это основные причины ошибки 404 при выполнении запроса с использованием Postman. Однако есть и другие возможные причины, которые могут быть уникальны для вашей собственной ситуации. Если вы продолжаете сталкиваться с проблемой 404, рекомендуется обратиться к документации вашего API или к разработчику, чтобы получить дополнительную помощь и поддержку.
В заключение, получение ошибки 404 при выполнении запроса с использованием Postman к Restful endpoint может быть вызвано несколькими факторами. Убедитесь, что вы правильно настроили конечную точку, метод запроса, аутентификацию и авторизацию, и проверьте доступность сервера API. Если проблема остается неразрешенной, обратитесь за помощью к документации или разработчику вашего API.
Skip to content
I am new to spring boot and i have been trying to get a simple api request via postman. But, I am stuck with an error 404. Can someone point the errors in my code?.
I have a spring boot simple app build with maven and run in embedded tomcat through STS. I tried to send this request
http://localhost:8080/api/vi/menu/getAll
Here is my controller code:
@RestController
@RequestMapping("/api/v1/menu")
public class MenuController {
@Autowired
private MenuRepository menuRepository;
@GetMapping
@RequestMapping("/getAll")
public List<Menu> list() {
return menuRepository.findAll();
}
}
MenuRepository:
public interface MenuRepository extends JpaRepository<Menu, Integer> {}
The error status in postman:
{
«timestamp»: «2022-08-05T04:46:28.489+00:00»,
«status»: 404,
«error»: «Not Found»,
«path»: «/api/vi/menu/getAll»
}
The port is in default 8080.
I tried adding url to the getmapping after referring some online documentations, but still the error 404 is not resolved. Can someone point the error and explain me ?
Thanks.
>Solution :
You are calling wrong URL
/api/vi/menu/getAll
correct url is
/api/v1/menu/getAll
Change vi to v1