Correct way to consume 3rd party API with query in Django + React (Backend + Frontend)

Viewed 82

I'm using Django on my backend and React on my frontend. I want to consume the OpenWeatherMap API. For security reasons, I want to keep my API key on the backend. Currently, I have this working on my Django app. When a POST request is made, the Django view renders the information required from OpenWeatherMap. How can the user type the query in React, send the query to to the backend and get the results on the frontend?

I have a very hacky way of doing this currently:

  1. I POST (using axios) the city that the user enters in React to a REST API that I built in Django.
  2. The backend queries the OpenWeatherMap API with the city that the user enters and POSTs the data that it gets from OpenWeatherMaps back to my API.
  3. After this, the frontend uses a GET request on my API to show the information to the user.

I'm pretty sure this isn't the correct way to do this but I couldn't find any other questions on this, and I'm pretty new to web development.

1 Answers

First two steps are just fine. Instead of step 3. return the response from OpenWeather as a response to POST request from step 1. and resolve it in your React code.

On the second thought and to be fine with REST guidelines:

  1. use GET to call your API with user's provided city name (POST is usually called to create a new resource - it's just a convention)
  2. inside your API call OpenWeatherMap API with the city name
  3. return the result to your React app as a response to GET from point 1.

More on REST API guidelines: https://restfulapi.net/

Related