Define a model in models.py file for the forecast data that you want to store. For example:
python
from django.db import models
class Forecast(models.Model):
date = models.DateField()
temperature = models.DecimalField(max_digits=5, decimal_places=2)
description = models.CharField(max_length=200)
Define the serializer:
Create a serializer in serializers.py file that will be used to serialize and deserialize the forecast data:
python
from rest_framework import serializers
from .models import Forecast
class ForecastSerializer(serializers.ModelSerializer):
class Meta:
model = Forecast
fields = ['id', 'date', 'temperature', 'description']
Define the view:
Create a view in views.py file that will be used to handle HTTP requests and responses:
python
from rest_framework import viewsets
from .models import Forecast
from .serializers import ForecastSerializer
class ForecastViewSet(viewsets.ModelViewSet):
queryset = Forecast.objects.all()
serializer_class = ForecastSerializer
Define the URLs:
Create a urls.py file in the forecaster_api app directory and define the URL routes for the API:
python
from django.urls import include, path
from rest_framework import routers
from .views import ForecastViewSet
router = routers.DefaultRouter()
router.register(r'forecasts', ForecastViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Include the URLs:
Include the URL configuration in your project's urls.py file:
python
from django.urls import path, include
urlpatterns = [
path('api/', include('forecaster_api.urls')),
]
Now you can run your Django server and test your API using a tool such as Postman or cURL. For example, you can send a GET request to http://localhost:8000/api/forecasts/ to retrieve a list of forecasts.