Working with endpoints for the API

We want to create an endpoint for the root of our API to make it easier to browse the API with the browsable API feature and understand how everything works. Add the following code to the views.py file to declare the ApiRoot class. The code file for the sample is included in the restful_python_chapter_02_03 folder.

class ApiRoot(generics.GenericAPIView): 
    name = 'api-root' 
    def get(self, request, *args, **kwargs): 
        return Response({ 
            'players': reverse(PlayerList.name, request=request), 
            'game-categories': reverse(GameCategoryList.name, request=request), 
            'games': reverse(GameList.name, request=request), 
            'scores': reverse(PlayerScoreList.name, request=request) 
            }) 

The ApiRoot class is a subclass of the rest_framework.generics.GenericAPIView class and declares the get method. The GenericAPIView class is the base class for all the other generic views. The ApiRoot class defines the get method that returns a Response object with key-value pairs of string that provide a descriptive name for the view and its URL, generated with the rest_framework.reverse.reverse function. This URL resolver function returns a fully qualified URL for the view.

Go to the gamesapi/games folder and open the urls.py file. Replace the code in this file with the following code. The following lines show the code for this file that defines the URL patterns that specifies the regular expressions that have to be matched in the request to run a specific method for a class-based view defined in the views.py file. Instead of specifying a function that represents a view we call the as_view method for the class-based view. We use the as_view method. The code file for the sample is included in the restful_python_chapter_02_03 folder:

from django.conf.urls import url 
from games import views 
 
 
urlpatterns = [ 
    url(r'^game-categories/$',  
        views.GameCategoryList.as_view(),  
        name=views.GameCategoryList.name), 
    url(r'^game-categories/(?P<pk>[0-9]+)/$',  
        views.GameCategoryDetail.as_view(), 
        name=views.GameCategoryDetail.name), 
    url(r'^games/$',  
        views.GameList.as_view(), 
        name=views.GameList.name), 
    url(r'^games/(?P<pk>[0-9]+)/$',  
        views.GameDetail.as_view(), 
        name=views.GameDetail.name), 
    url(r'^players/$',  
        views.PlayerList.as_view(), 
        name=views.PlayerList.name), 
    url(r'^players/(?P<pk>[0-9]+)/$',  
        views.PlayerDetail.as_view(), 
        name=views.PlayerDetail.name), 
    url(r'^player-scores/$',  
        views.PlayerScoreList.as_view(), 
        name=views.PlayerScoreList.name), 
    url(r'^player-scores/(?P<pk>[0-9]+)/$',  
        views.PlayerScoreDetail.as_view(), 
        name=views.PlayerScoreDetail.name), 
    url(r'^$', 
        views.ApiRoot.as_view(), 
        name=views.ApiRoot.name), 
] 

When we coded our previous version of the API, we replaced the code in the urls.py file in the gamesapi folder, specifically, the gamesapi/urls.py file. We made the necessary changes to define the root URL configuration and include the URL pattern declared in the previously coded games/urls.py file.

Now, we can launch Django's development server to compose and send HTTP requests to our still unsecure, yet much more complex Web API (we will definitely add security later). Execute any of the following two commands based on your needs to access the API in other devices or computers connected to your LAN. Remember that we analyzed the difference between them in Chapter 1, Developing RESTful APIs with Django:

python manage.py runserver
python manage.py runserver 0.0.0.0:8000

After we run any of the previous commands, the development server will start listening at port 8000.

Open a web browser and enter http://localhost:8000/ or the appropriate URL in case you are using another computer or device to access the browsable API. The browsable API will compose and send a GET request to / and will display the results of its execution, that is, the headers and the JSON response from the execution of the get method defined in the ApiRoot class within the views.py file. The following screenshot shows the rendered web page after entering the URL in a web browser with the resource description: Api Root.

The API Root provides us hyperlinks to see the list of game categories, games, players, and scores. This way, it becomes extremely easy to access the lists and perform operations on the different resources through the browsable API. In addition, when we visit the other URLs, the breadcrumb will allow us to go back to the Api Root.

In this new version of the API, we worked with the generic views that provide many featured under the hoods, and therefore, the browsable API will provide us additional features compared with the previous version. Click or tap on the URL on the right-hand side of game-categories. In case you are browsing in localhost, the URL will be http://localhost:8000/game-categories/. The browsable API will render the web page for the Game Category List.

At the bottom of the rendered web page, the browsable API provides us some controls to generate a POST request to /game-categories/. In this case, by default, the browsable API displays the HTML form tab with an automatically generated form that we can use to generate a POST request without having to deal with the raw data as we did in our previous version. The HTML forms make it easy to generate requests to test our API. The following screenshot shows the HTML form to create a new game category:

Working with endpoints for the API

We just need to enter the desired name, 3D RPG, in the Name textbox and click or tap on POST to create a new game category. The browsable API will compose and send a POST request to /game-categories/ with the previously specified data and we will see the results of the call in the web browser. The following screenshot shows a web browser displaying the HTTP status code 201 Created in the response and the previously explained HTML form with the POST button to allow us to continue composing and sending POST requests to /game-categories/:

Working with endpoints for the API

Now, click on the URL displayed as a value for the url key in the JSON data displayed for the game category, such as http://localhost:8000/game-categories/3/. Make sure you replace 2 with the id or primary key of an existing game category in the previously rendered Games List. The browsable API will compose and send a GET request to /game-categories/3/ and will display the results of its execution, that is, the headers and the JSON data for the game category. The web page will display a DELETE button because we are working with the Game Category Detail view.

Tip

We can use the breadcrumb to go back to the Api Root and start creating games related to a game category, players, and finally scores related to a game and a player. We can do all this with easy to use HTML forms and the browsable API feature.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.62