Consuming the API
By making our views available via URLs, we have created our first API endpoints. Let’s now try our own API. Ensure that your server is running with the following command:
python manage.py runserver
We are going to use curl
to consume the API. curl
is a command-line tool that allows you to transfer data to and from a server. If you are using Linux, macOS, or Windows 10/11, curl
is very likely included in your system. However, you can download curl
from https://curl.se/download.html.
Open the shell and retrieve the URL http://127.0.0.1:8000/api/subjects/
with curl
, as follows:
curl http://127.0.0.1:8000/api/subjects/
You will get a response similar to the following one:
[
{
"id":1,
"title":"Mathematics",
"slug":"mathematics"
},
{
"id":2,
"title":"Music",
"slug":"music"
},
{
"id":3,
"title":"Physics",
"slug":"physics"
},
{
"id":4,
"title":"Programming",
"slug":"programming"
}
]
To obtain a more readable, well-indented JSON response, you can use curl
with the json_pp
utility, as follows:
curl http://127.0.0.1:8000/api/subjects/ | json_pp
The HTTP response contains a list of Subject
objects in the JSON format.
Instead of curl
, you can also use any other tool to send custom HTTP requests, including a browser extension such as Postman, which you can get at https://www.getpostman.com/.
Open http://127.0.0.1:8000/api/subjects/
in your browser. You will see DRF’s browsable API, as follows:
Figure 15.2: The Subject List page in the REST framework browsable API
This HTML interface is provided by the BrowsableAPIRenderer
renderer. It displays the result headers and content, and it allows you to perform requests. You can also access the API detail view for a Subject
object by including its ID in the URL.
Open http://127.0.0.1:8000/api/subjects/1/
in your browser. You will see a single Subject
object rendered in the JSON format.
Figure 15.3: The Subject Detail page in the REST framework browsable API
This is the response for the SubjectDetailView
. Let’s learn how to enrich the content returned for each subject. In the next section, we are going to dive into extending serializers with additional fields and methods.