HTTP / LESSON 02

Anatomy of a URL

Take a URL apart, and learn how to pass values in the query string.

A URL names a resource and says how to reach it. Designing URLs is a big part of designing an API, so it's worth knowing each part.

The parts of a URL

https://api.rest.pipal.in:443/api/contacts?name=Asha&mobile=98#results
\___/   \_______________/ \_/\___________/ \________________/ \_____/
scheme        host        port    path          query         fragment
Part Example What it does
Scheme https Says which protocol to use
Host api.rest.pipal.in Says which server to talk to
Port 443 Says which port on that server to connect to
Path /api/contacts Says which resource you want
Query name=Asha&mobile=98 Passes extra parameters to the server
Fragment results Points to a place in the page, for the client's use

You'll rarely see the port, because each scheme has a default: 80 for http and 443 for https.

The client uses the fragment itself and never sends it to the server. So it has no use in most APIs, and the runnable cells in this course reject URLs that have one.

The path

The path identifies a resource. Compare these two requests:

The first returns all the contacts, and the second returns one contact.

Experiment: Change /api/contacts/123 to /API/contacts/123, and then to /api/contacts/123/. What happens? To a server, each path is its own string, so small differences can matter.

The query

The query comes after the ?. It's a list of name=value pairs, separated by &. The Contacts API uses it for searching.

Request headers 0

Your turn: Search for contacts whose mobile numbers start with 98, using the mobile parameter. Then combine name and mobile in one search.

Try a search that matches nothing, such as name=zzz. You get 200 OK and an empty list. The search worked, and it found no contacts.

Special characters

Some characters have a special meaning in a URL, so they can't appear as they are inside a value. To use one, write % and then its character code in hexadecimal. This is called percent-encoding.

Character Encoded
Space %20
& %26
= %3D
? %3F
# %23
% %25

This request sends the text Tom & Jerry to the FIGlet API.

Break it on purpose: Replace %26 with a plain &. What comes back? Why did Jerry disappear?

Quote your URLs

In a terminal, & tells the shell to run a command in the background. Without quotes, the shell cuts this command short, and the server never receives b=4:

curl https://numbers.apps.pipal.in/add?a=3&b=4

So always put quotes around a URL:

curl 'https://numbers.apps.pipal.in/add?a=3&b=4'

Your turn: Run both commands in your terminal, and compare the results.

Summary

  • A URL has a scheme, a host, a port, a path, a query, and a fragment.
  • The path identifies a resource, and the query passes parameters.
  • Encode special characters in values, and put quotes around URLs in a terminal.

Next, we'll look at the messages that travel between a client and a server.