You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

REST-API概念解析及Django电影POST接口实现技术咨询

Hey there! Let's break this down nice and slow since you're new to Django and navigating REST APIs—no fancy jargon that doesn't stick, promise.

First: What's a REST API?

At its core, a REST API is a set of simple rules that let different software applications talk to each other over the internet. Think of it like a menu and waiter combo: you send a specific request (using standard HTTP methods like POST, GET, etc.)—say, "I want details for the movie 'Inception'"—and the API sends back a structured response (like JSON with the movie's release year, director, plot, etc.) or tells you if it can't fulfill your request. It's the backbone of most modern web services that share data between apps.


Now: Building the POST /movies Endpoint

I'll assume you're using Django REST Framework (DRF) here—it's the go-to tool for building APIs in Django, especially for beginners. Let's split this into 3 key parts: validating the title, fetching data from the public movie API, and saving/returning the movie data.

1. Setup First: Install Dependencies & Create Your Movie Model

First, make sure you have DRF and requests (for calling external APIs) installed:

pip install djangorestframework requests

Then define your Movie model in models.py—map fields to what you'll get from the public movie API (I'll use OMDB as an example):

from django.db import models

class Movie(models.Model):
    title = models.CharField(max_length=255, unique=True)
    year = models.CharField(max_length=10)  # OMDB returns year as string sometimes
    director = models.CharField(max_length=255)
    plot = models.TextField()
    poster_url = models.URLField(blank=True)
    imdb_id = models.CharField(max_length=20, unique=True)

    def __str__(self):
        return self.title

2. Validate the Title (Existence & Request Format)

We need two layers of validation here:

  • Ensure the incoming request has a title field (no empty requests)
  • Verify that the title actually exists in the public movie API

First, create a serializer in serializers.py—this handles request validation and data serialization:

from rest_framework import serializers
from .models import Movie
import requests

class MovieCreateSerializer(serializers.ModelSerializer):
    # Only expose the title field for the POST request
    class Meta:
        model = Movie
        fields = ['title']

    def validate_title(self, value):
        # Optional: Check if the movie is already in our database to avoid duplicates
        if Movie.objects.filter(title__iexact=value).exists():
            raise serializers.ValidationError("This movie is already in our database.")
        
        # Check if the title exists in the public API (OMDB example)
        # Replace YOUR_OMDB_API_KEY with your actual free key from the OMDB service
        omdb_response = requests.get(
            "http://www.omdbapi.com/",
            params={"t": value, "apikey": "YOUR_OMDB_API_KEY"}
        )
        omdb_data = omdb_response.json()

        # OMDB returns "Response": "False" if the movie isn't found
        if omdb_data.get("Response") == "False":
            raise serializers.ValidationError(f"Movie with title '{value}' not found in public database.")
        
        # Store the OMDB data in the serializer context for later use
        self.context['omdb_data'] = omdb_data
        return value

3. Fetch Data from the Public API & Save to Your Database

Now build the view in views.py to handle the POST request:

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import MovieCreateSerializer
from .models import Movie

class MovieCreateView(APIView):
    def post(self, request):
        serializer = MovieCreateSerializer(data=request.data)
        if serializer.is_valid():
            # Grab the pre-fetched OMDB data from the serializer context
            omdb_data = serializer.context['omdb_data']
            
            # Create the Movie object using the OMDB data
            movie = Movie.objects.create(
                title=omdb_data['Title'],
                year=omdb_data['Year'],
                director=omdb_data['Director'],
                plot=omdb_data['Plot'],
                poster_url=omdb_data.get('Poster', ''),
                imdb_id=omdb_data['imdbID']
            )

            # Return the full movie data (you can use a separate serializer for this if needed)
            full_serializer = serializers.ModelSerializer(movie, model=Movie, fields='__all__')
            return Response(full_serializer.data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

4. Wire Up the URL

Add this to your urls.py to map the endpoint:

from django.urls import path
from .views import MovieCreateView

urlpatterns = [
    path('movies/', MovieCreateView.as_view(), name='create-movie'),
]

Key Tips for Production

  • Handle Network Errors: Wrap the requests.get call in a try/except block to catch timeouts or connection errors (e.g., requests.exceptions.RequestException), and return a friendly error response.
  • Cache External API Calls: Use Django's caching framework to store OMDB responses for a few hours—this avoids hitting rate limits and speeds up your endpoint.
  • Use Environment Variables: Never hardcode your OMDB API key! Use a tool like python-dotenv to store it in a .env file and load it into your settings.
  • Rate Limiting: Add rate limiting to your DRF view to prevent abuse of your endpoint.

内容的提问来源于stack exchange,提问作者Eliro

火山引擎 最新活动