Web Development
From a city search to tomorrow’s forecast.
Type “Rajkot” into a weather app and the app can ask a server for the forecast through an API. The app sends an HTTP request that identifies the forecast it wants. The server replies with a status code and, if the request succeeds, data the app can turn into forecast cards. Following that exchange step by step shows what a REST API provides and what the app still has to do.
What the weather app and the API each do
The app is the client. It collects your search, sends requests, and decides how to display the results. The server receives those requests and sends back responses. The application programming interface, or API, is the contract between them. It tells the app what it can ask for, how to ask, and what the reply will look like.
For example, the contract might say that a forecast request must include a location identifier and can optionally specify the number of days and the preferred units. A successful reply might contain the location’s name and a list of daily forecasts. A mobile app can turn that list into swipeable cards. A desktop dashboard can display the same list in a table. Both clients can use the same API.
REST stands for Representational State Transfer. It’s an architectural style that treats things such as a location or a forecast as resources and uses standard interactions to work with their representations. In this example, JSON is the representation the server sends back. REST APIs can use other formats. The term “REST API” is also used loosely in practice, so the name alone tells you less than the documentation about what a particular service supports.
First, turn the search term into a location
A city name is useful for people, but it can be ambiguous for software. Several places can
share the same name, and someone may type a partial name or leave out the region. A weather
app can first call a location-search endpoint, such as /v1/locations?q=Rajkot.
Our fictional API returns a matching place with an ID, a region, and a country. The app
shows “Rajkot, Gujarat, India” so the user can confirm the selection.
After selection, the app uses the ID rajkot-in in the forecast request. That
tells the server exactly which location it should use. Other APIs may take latitude and
longitude instead. Either way, the location that appears on the screen and the value
sent to the forecast endpoint serve different purposes. One helps a person recognise the
place. The other lets the server locate the right data.
Imagine the search returns three places with the same name. The app can display them with their regions and wait for a choice. If the search succeeds but returns an empty list, the app can suggest another spelling. At that point, it hasn’t asked for weather yet. Keeping location search separate from forecast retrieval makes it easier to tell users which step needs their attention.
Next, send a GET request for the forecast
Once the user picks a city, the app has enough information to request the weather. It uses GET because it wants to read data. In this example, the forecast path identifies the location, while the options after the question mark ask for two days in metric units. Here’s what that request could look like in HTTP/1.1 syntax.
GET /v1/locations/rajkot-in/forecast?days=2&units=metric HTTP/1.1
Host: weather.example
Accept: application/json
Method
GET asks the server to return a representation of the requested resource.
Path and query
The path names the location’s forecast. days and units specify the version the app wants.
Headers
Host identifies the target server. Accept expresses a preference for JSON.
Notice that the forecast request includes the location ID even though the app just searched for the city. In a stateless REST interaction, the server can understand the request without remembering which search the client made earlier. The app can keep Rajkot selected on the screen. The server can keep weather records in a database. Statelessness concerns the interaction between requests. Each request carries the context needed to handle it, including credentials when the API requires them.
When you build URLs in JavaScript, use tools such as URL and
URLSearchParams to assemble query values. A city like “New Delhi”
contains a space, and other searches can contain punctuation with a special meaning
in a URL. Letting the URL tools encode those values avoids a problem that may
never show up while you’re testing with a short city name.
The server returns a status, headers, and data
The server checks the request and locates the forecast. It could read a stored forecast or obtain one from another service. The app’s request looks the same either way. If the server can supply the requested data, it sends back a response with a success status. The example below uses fictional weather values and an illustrative response format.
HTTP/1.1 200 OK
Content-Type: application/json
{
"location": {
"id": "rajkot-in",
"name": "Rajkot",
"region": "Gujarat",
"timeZone": "Asia/Kolkata"
},
"temperatureUnit": "C",
"daily": [
{
"date": "2026-12-01",
"high": 29,
"low": 17,
"condition": "Sunny"
},
{
"date": "2026-12-02",
"high": 28,
"low": 16,
"condition": "Partly cloudy"
}
]
}
200 OK indicates that the GET request succeeded. The
Content-Type header tells the client what format the body uses. The body
contains the data itself. Here it’s a JSON object with location details and a
daily array. Each item in that array describes one forecast date.
A real provider may use different field names or return hourly forecasts alongside
the daily ones. Use its documentation to find the fields your screen needs.
Read each field in context. The number 29 becomes meaningful once you know
it’s a daily high expressed in Celsius. The forecast date belongs to the location’s
calendar. If someone in another time zone looks up Rajkot and the app labels a card
“Tomorrow,” that label should reflect the selected location’s date. Otherwise the app
can show a correct temperature under the wrong day.
Turn the JSON into something someone can read
The server returns the forecast as data. The app chooses the order of the cards, formats the dates, adds degree symbols, and puts the condition where people can see it. It might show both the high and low on a large screen and lead with the high on a compact widget. The client can make those choices without asking the server for a different visual layout.
December 1 · Rajkot
29°C high · 17°C low
Sunny
December 2 · Rajkot
28°C high · 16°C low
Partly cloudy
Decide how to display missing fields before the first real request. For example, if the service supplies the high but omits the low for one date, the card can show the available value and mark the low as unavailable. Filling the gap with zero would present a plausible-looking temperature that the service never sent. Treat missing data as a display case of its own.
Also consider what happens when the user changes cities quickly. The request for the first city can finish after the request for the second. If every response immediately replaces the screen, the app can end up showing Rajkot’s forecast under another city’s name. Cancel the earlier request when possible or check that the response still matches the current selection before displaying it.
What requesting the forecast looks like in JavaScript
The function below calls /api/forecast on the same site as the app.
In a real project, you would implement that route on your backend. It could serve
sample data while you build the screen and call a weather provider once you connect
it to live data. Keeping the browser request on your own site also gives you a place
to hold a provider credential on the server if one is required.
async function loadForecast(locationId, signal) {
const query = new URLSearchParams({
location: locationId,
days: "2",
units: "metric"
});
const response = await fetch(`/api/forecast?${query}`, {
headers: { Accept: "application/json" },
signal
});
if (!response.ok) {
throw new Error(`Forecast request failed (${response.status}).`);
}
const forecast = await response.json();
if (!Array.isArray(forecast?.daily)) {
throw new Error("The forecast is missing its daily data.");
}
return forecast;
}
The app can show a loading message while the function runs. If it returns a forecast, update the cards. If it fails, the caller can decide what to show. A cancelled request from a city the user has already left can be ignored. A failed request for the city still selected should leave a visible message and a way to try again.
One detail catches beginners: fetch() can return a response even when the
server sends an HTTP error such as 404. The check on response.ok handles
that case before the app reads the expected forecast data. A network failure can
reject the request before a response arrives. Reading the body can fail separately
if the response contains malformed JSON. Those failures all belong in the app’s
error-handling flow.
Use the response to decide what the user sees next
A failed forecast is easier to handle once you know which step went wrong. Invalid input calls for a correction. A temporarily unavailable service calls for a different message. The exact status codes and error bodies depend on the API’s contract. These examples show how a weather app could respond to common outcomes.
| Response | Example cause | App behaviour |
|---|---|---|
| 200 OK | Forecast returned. | Read the data and render the cards. |
| 400 Bad Request | An unsupported value was sent for days. |
Correct the value before sending the request again. |
| 404 Not Found | The requested location resource doesn’t exist. | Let the user return to location search. |
| 429 Too Many Requests | The client reached a rate limit. | Wait before retrying and respect any retry guidance. |
| 503 Service Unavailable | The service is temporarily unable to handle the request. | Show a temporary failure message and allow a later retry. |
A search request with no matches and a forecast request for an unknown ID can have
different outcomes. The search endpoint may return 200 OK with an empty
list because it successfully completed the search. The forecast endpoint may return
404 for a location the API doesn’t recognise. On screen, the first can say
“No matching locations.” The second can say “This location is unavailable. Choose
another city.”
If the app already has a forecast for the selected city, it can sometimes keep those cards visible when a refresh fails. Show when they were last updated so the user can tell how old the data is. If it has never loaded a forecast for that city, give the user a clear retry action. In both cases, the screen should make it clear whether it has usable data from a previous request.
Decide when the app actually needs another request
Suppose the user opens Rajkot, checks another city, then returns to Rajkot a few seconds later. The app could request the same forecast twice. If the previous response is still fresh under the service’s cache policy, the app or browser may be able to reuse it. That can make the screen load faster and reduce requests to the server. Forecasts change over time, so the age limit matters.
Store enough information to distinguish different forecasts. Two days in metric units and seven days in another unit system represent different requests. If the app stores only the location ID with the response, it could recover the right city with the wrong forecast length or units. When you reuse data, check the location and all options that affect the representation.
Location search has a separate issue. If the app automatically searches as someone types, it can wait briefly for a pause before sending the query. The user who types “Rajkot” in one motion may then trigger one search instead of a separate request for every letter. Once the user chooses a result, the app can make the forecast request immediately because it has the location it needs.
Follow the exchange in your browser
When you have a working forecast endpoint, open the browser’s developer tools and select the Network panel. Run a city search, then select a location. Find the forecast request and inspect its URL, method, and status. Open the response body and compare the location ID and the first forecast date with what appears on the page. This gives you a way to investigate a wrong card without guessing where the mistake started.
If the response contains correct values but the screen shows the wrong units, look at the client’s formatting. If the request itself asks for the wrong units, trace how the app built the URL. If the server replied with an error, read that response and see how the app handled it. Checking the request, response, and screen in that order separates three problems that can all look like “the weather app is broken.”
Start your first version with one location, one successful forecast, and one failure state. Once you can follow those cases from the button press to the network request and back to the screen, add location search and unit selection. Each feature gives the client new information to send or a new way to present the reply. The same exchange still drives the app.


