- Restful API ๋?
- query parameter
- path parameter
- ์ฃผ์ ์ฌํญ
API์์ ์ ์กํ๋ resource๋ฅผ URI๋ก ํํํ๊ณ ํด๋น ์์์ ํํ๊ณ ์ ํ๋ ์๋๋ฅผ HTTP ๋ฉ์๋๋ก ์ ์.
GET method ์ ํด๋นํ๋ url ์ ๋ํด filtering, paging ํ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ๊ณ ์ถ์ ๊ฒฝ์ฐ ์ฌ์ฉ. ์ฃผ๋ก ๋ฌดํ scroll ํ๋ฉด์์ ์์ฃผ ์ฌ์ฉ.
GET http://localhost:8000/places?id=1®ion=์์ธ # filtering GET http://localhost:8000/places?offset=0&limit=100 # paging
django view์์ ์๋์ ๊ฐ์ด ์ฒ๋ฆฌํ๋ค.
class PlacesView(): def get(self, request): id = request.GET.get(id, None) region = request.GET.get(region, None) offset = request.GET.get(offset, None) limit = request.GET.get(limit, None)
๊ฐ์ด ์๋๊ฒ ํ์คํ๋ค๋ฉด request.GET['id'] ๋ฐฉ์๋ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
ํ๋์ ์์์ ๋ํ GET, PATCH(update), DELETE method์ ํด๋นํ๋ url์ ๊ฒฝ์ฐ ์ฌ์ฉํ๋ ๋ฐฉ์
http://localhost:8000/place/places/1 http://localhost:8000/place/places/์๋ฃธ
django view์์ ์๋์ ๊ฐ์ด ์ฒ๋ฆฌํ๋ค.
from django.urls import path from . import views urlpatterns = [ path('/places/<int:place_id>', views.GetDetailPlaceView), path('/places/<str:category>', views.GetPlaceWithCategoryView), ]
์ด๋ฅผ View์์ ์ฒ๋ฆฌํ๋ ์ฝ๋๋ ์๋์ ๊ฐ๋ค.
class GetDetailPlaceView(): def get(self, request, place_id): place = Place.objects.filter(id=place_id) return JsonResponse({"place":place.values()}, status=200) class GetPlaceWithCategoryView(): def get(self, request, category): categories = Category.objects.prefetch_related('place_set').all() places = [category.place_set.values() for category in categories] return JsonResponse({"place":places}, status=200)
url parameter ๋ฐฉ์์ ์ฌ์ฉํ ๋๋ get, post ๋ฉ์๋์ parameter์ urls์์ ์ ์ธํ ๋ณ์๋ช ์ ์ถ๊ฐํ๋ฉด ๋๋ค.
- url์ resource ๊ธฐ์ค์ผ๋ก ๊ฐ์ผํ๋ค.
- Method๊ฐ ์์ผ๋ฏ๋ก ๋์ฌ๋ฅผ ์ฐ์ง ์๋๋ค.(๋์ ์. /get_places)