๐Ÿ”ฅTIL#9. RESTful API

๋ฐฑ์Šน์ง„ยท2020๋…„ 11์›” 23์ผ
0

wecode Django ์‹ค์Šต

๋ชฉ๋ก ๋ณด๊ธฐ
11/16

Today I learned

  1. Restful API ๋ž€?
  2. query parameter
  3. path parameter
  4. ์ฃผ์˜ ์‚ฌํ•ญ

1. Restful API

API์—์„œ ์ „์†กํ•˜๋Š” resource๋ฅผ URI๋กœ ํ‘œํ˜„ํ•˜๊ณ  ํ•ด๋‹น ์ž์›์— ํ–‰ํ•˜๊ณ ์ž ํ•˜๋Š” ์˜๋„๋ฅผ HTTP ๋ฉ”์†Œ๋“œ๋กœ ์ •์˜.

2. query parameter

GET method ์— ํ•ด๋‹นํ•˜๋Š” url ์— ๋Œ€ํ•ด filtering, paging ํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ ์‚ฌ์šฉ. ์ฃผ๋กœ ๋ฌดํ•œ scroll ํ™”๋ฉด์—์„œ ์ž์ฃผ ์‚ฌ์šฉ.

GET http://localhost:8000/places?id=1&region=์„œ์šธ		# 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'] ๋ฐฉ์‹๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.

3. path parameter

ํ•˜๋‚˜์˜ ์ž์›์— ๋Œ€ํ•œ 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์—์„œ ์„ ์–ธํ•œ ๋ณ€์ˆ˜๋ช…์„ ์ถ”๊ฐ€ํ•˜๋ฉด ๋œ๋‹ค.

4. ์ฃผ์˜ ์‚ฌํ•ญ

  1. url์€ resource ๊ธฐ์ค€์œผ๋กœ ๊ฐ€์•ผํ•œ๋‹ค.
  2. Method๊ฐ€ ์žˆ์œผ๋ฏ€๋กœ ๋™์‚ฌ๋ฅผ ์“ฐ์ง€ ์•Š๋Š”๋‹ค.(๋‚˜์œ ์˜ˆ. /get_places)
profile
12๋…„ .NET ๊ฐœ๋ฐœ ๊ฒฝ๋ ฅ์„ ๊ฐ€์ง„ ์›น ์ดˆ์งœ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค :)

0๊ฐœ์˜ ๋Œ“๊ธ€