A web service is meant to be consumed by a client. Clients can have many different forms: a mobile app, a command-line utility, a desktop application, or a website. If your software can issue HTTP requests, it can be the client of a web service.
To make a webpage that communicates with a web service, you use JavaScript and the browser's builtin fetch
function. Consider this GET
request that retrieves a post from the JSONPlaceHolder mock web service:
Explore the documentation of the JSONPlaceholder service. Try retrieving a different post. Try retrieving all posts. Try retrieving all users.
To delete post 17, you issue a DELETE
request to URL /posts/17
. A plain call to fetch
issues a GET
request. You override this default by specifying the desired method in a second parameter:
This mock web service doesn't actually delete the post, but a real one would.
To create a new post, you issue a POST
request to URL /posts
. The properties of the post are too big and gangly to be sent as URL parameters. Instead, you create a post object with title
, body
, and userId
properties and serialize it to JSON. The JSON is sent as the body of the request. Additionally, you add a Content-Type
header to declare the format of the body:
Note how the service adds to the response the ID it generates for the new post.
To modify existing post 23, you issue a PATCH
request to URL /posts/23
. The modified post properties are sent as a JSON payload:
Note how the service gives back the complete post record.