1. Making GET Requests with Curl
Curl, short for Client for URLs, is a command line tool that allows us to transfer data to and from a server. It supports multiple protocols, including HTTP. You can read more about curl in our “What is curl?” article.
curl localhost:4001/restaurants
2. Post Request
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Restaurant addRestaurant(@RequestBody Restaurant restaurant) {
validateNewRestaurant(restaurant);
return restaurantRepository.save(restaurant);
}
3. Post Request with Curl
curl -X POST -d "{\"name\":\"Charlie\", \"breed\":\"German Shepherd\"}" -H "Content-Type: application/json" http://www.mypetclinic.com/dogs/
- -X POST tells the server that the client is making a POST request, where -X is the curl parameter specifying the type of request method to use.
- -d (short for --data) indicates to the server that the client is sending new data to an existing application.
The content inside "{ }", \"name\":\"Charlie\", \"breed\":\"German Shepherd\" , is the data that the client wants to send (as indicated by the preceding -d). We use the {\"key1\":\"value1\", \"key2\":\"value2\"} syntax, where name and breed are the names of the two keys that define the dog object, and “Charlie” and “German Shepherd” are the values corresponding to those keys respectively.
- -H "Content-Type: application/json" specifies that we are sending data in JSON format.
- Finally, the URL http://www.mypetclinic.com/dogs/ tells the server where to send this new data. In this case, the newly-created dog object will be posted under the dogs resource.
4. Exception Handling
ResponseStatusException accepts up to 3 arguments:
- HttpStatus code
- String reason
- Throwable cause
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus
curl -X PUT -d '{"id":"350", "date":"03/17/2018", "country":"Poland", "city":"Sadowie", "state":"", "numPhotos":5,"blogCompleted":false}' -H "Content-Type:application/json" localhost:4001/traveladventures/350