Skip to content

API Request

Adrien Bocquet edited this page Jan 15, 2020 · 3 revisions

Making requests

The site is build around a frontend and a backend that are distinct (they are respectively managed by Django and React). However, it's obvious they have to communicate in order to make the website work properly. Let's see how one should implement such communication.

Server side

The most common operations that will be performed will be the CRUD requests (Create, Read, Update, Delete). One should avoid at all cost to reinvent the wheel by using the Django REST framework (http://www.django-rest-framework.org). It provides powerful predefined methods to perform the CRUD operations and thus allows to write less code, that is therefore easier to maintain and less buggy.

The URL to query the REST resource is in the following form : /api/v1/<model>/[<id>] where model can be association, polls ..., and id is a facultative parameter.

Client side

Making requests

API requests are made with Axios from the client. To make requests from React, use the api object in frontend/src/services/apiService.ts. For instance, to query all associations, use

api.associations.list()
.then(associations => { // Use the response
     doStuff(associations);
     doOtherStuff(associations);
})
.catch(err => alert(err.message)) // In case of error, please always take this case into account

Adding a new endpoint

To add a model query, add a sub-object in the api object, then a function named according to the wanted action. Please use list, get, save, and delete if you're doing common operations (i.e. in most of the cases). Apply unwrap<ObjectType> on the axios result unpacks the value returned by axios and allows you to use the static typing of Typescript.