Welcome back, coding enthusiasts! Today, we're diving into Function-Based API Views in Django. This is a powerful tool for building web APIs with Django and we're excited to show you how it works.
Let's start with the basics.
Function-Based API Views are a simple and flexible way to define views in Django. Unlike Class-Based Views, they are just regular Python functions that return an HttpResponse object or a shortcut for creating one. This makes them easier to write, test, and debug.
💡 Pro Tip: Function-Based Views are perfect for simple APIs and can be a great starting point for complex ones too!
Let's create a simple Function-Based API View to return a list of books.
from django.http import JsonResponse
def book_list(request):
books = [
{'title': 'The Catcher in the Rye', 'author': 'J.D. Salinger'},
{'title': 'To Kill a Mockingbird', 'author': 'Harper Lee'},
{'title': '1984', 'author': 'George Orwell'},
]
return JsonResponse(books, safe=True)In the above example, book_list is our Function-Based View. It returns a JSON response containing a list of books. The safe=True argument ensures that JSON is safe to parse.
Now, let's set up a URL to access this view.
We'll create a new URL pattern for our book_list view in the urls.py file of our app.
from django.urls import path
from . import views
urlpatterns = [
path('api/books/', views.book_list, name='book_list'),
]Now, if you navigate to /api/books/ in your browser, you'll see our list of books!
To retrieve a single book, we'll create another Function-Based View, book_detail.
def book_detail(request, pk):
try:
book = list(filter(lambda book: book['pk'] == int(pk), books))[0]
except IndexError:
return JsonResponse({'error': 'Book not found.'}, status=404)
return JsonResponse(book)In this example, pk is the primary key of the book we're trying to retrieve. If the book isn't found, we return a 404 status code with an error message.
Now, let's add a new URL pattern for book_detail.
urlpatterns = [
# ...
path('api/books/<int:pk>/', views.book_detail, name='book_detail'),
]With this, you can now access individual books by their primary key, e.g., /api/books/1/.
What does the `safe=True` argument do in the `JsonResponse` function?
That's it for today! In the next lesson, we'll dive deeper into Function-Based API Views, including handling multiple requests and creating dynamic views.
Until then, happy coding! 🎯