顯示具有 RESTful API 標籤的文章。 顯示所有文章
顯示具有 RESTful API 標籤的文章。 顯示所有文章

2019年3月23日 星期六

[Vue.js] 安裝axios對後端傳送Request (GET/POST/PUT/DELETE)


安裝指令
npm install axios

使用方式
import axios from 'axios'
// use axios in your project
// ...
1. GET
[URL] 字串、API位址
[HEADER] dict,例如:{'Content-Type': 'multipart/form-data'}。
[PARAM] dict,例如:{'id': '1'},等同於?id=1。
axios.post('[URL]', {headers:[HEADER], params: [PARAM]})
    .then(response => {
        console.log(response);
    })
    .catch(err => {
        console.log(err.response);
    });
2. POST
[DATA] 資料
axios.get('[URL]', [DATA], {headers:[HEADER]})
    .then(response => {
        console.log(response);
    })
    .catch(err => {
        console.log(err.response);
    });
3. PUT
格式與post相同
axios.put('[URL]', [DATA], {headers:[HEADER]})
    .then(response => {
        console.log(response);
    })
    .catch(err => {
        console.log(err.response);
    });
4. DELETE
axios.delete('[URL]', {headers:[HEADER], data:[DATA]})
    .then(response => {
        console.log(response);
    })
    .catch(err => {
        console.log(err.response);
    });

與 vue-resource 比較不同的是error handling,API回應中通常包含http_statsu、body、data等,success handling回傳的就是標準的回應,但error handling放在response這個key裡面。舉例要取得http_status,在success handling裡是response[http_status],但error handling是err.response[http_status]。


2019年1月6日 星期日

[Vue.js] 安裝vue-resource執行POST, GET


vue官方之前推薦使用vue-resource套件來執行HTTP Request,不過vue更新到2.0之後,作者就宣告不再更新vue-resource,目前漸漸被axios取代。所以這篇只是做為紀錄性質,寫一下使用vue-resource的方法。

請先用指令npm安裝vue-resource
$ npm install vue-resource

先在專案中加入這個套件
# src/main.js
import VueResource from 'vue-resource'
Vue.use(VueResource)

請根據需求設定{URL} {BODY} {HEADER}

1. GET
this.$http({
 url: {URL},
 method: 'GET',
 body: {},
 headers: {HEADER}
 }).then(function (response) {
  console.log('success');
 }, function (response) {
  console.log('fail');
});

2. POST
this.$http.post({URL}, {BODY}, {HEADER}).then(
 function (response) {
  console.log('success');
 }, function (response) {
  console.log('fail');
});
this.$http({
 url: {URL},
 method: 'POST',
 body: {BODY},
 headers: {HEADER}
 }).then(function (response) {
  console.log('success');
 }, function (response) {
  console.log('fail');
});

2018年1月28日 星期日

[Django] REST framework

首先必須安裝rest framework
# install django rest framework
pip install djangorestframework
在settings.py加上rest_framework
# project/settings.py
INSTALLED_APPS = (
    ...
    'app',
    'rest_framework',
)
準備資料表
# app/models.py
from django.db import models
def Participant():
    name = models.CharField(max_length=20)
    age = models.DecimalField(max_digits=3,decimal_places=0)
    GENDER = (
        ('F', 'Female'),
        ('M', 'Male'),
    )
    gender = models.CharField(max_length=1, choices=GENDER)

初始資料表或更新時,執行makemigrations產生model.py的資料庫語言,執行migrate則會根據這份文件去建立/修改資料表。shell指令則是進入Python的互動模式去操作資料庫。
# active model
python manage.py makemigrations
python manage.py migrate

# execute python shell
python manage.py shell
# (Python Shell)add a new record in Participant
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from app.models import Participant
>>> record = Participant(name='Mike', age='20', gender='M')
>>> record.save()
serializers.py
# app/serializers.py
from rest_framework import serializers
from app.models import Participant

class ParticipantSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Participant
        fields = ('url', 'name', 'age', 'gender')
views.py
# app/views.py
from rest_framework import viewsets
from app.models import Participant
from app.serializers import ParticipantSerializer

class ParticipantViewSet(viewsets.ModelViewSet):
    queryset = Participant.objects.all()
    serializer_class = ParticipantSerializer
url.py
# project/url.py
from django.conf.urls import url, include
from rest_framework import routers
from app.views import ParticipantViewSet

router = routers.DefaultRouter()
router.register(r'participants', ParticipantViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    ...
    url(r'^api/', include(router.urls)),
    url(r'^api/api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

接著就可以在瀏覽器上確認API有沒有正常運作。

URL- http://www.example.com.tw/api/

URL- http://www.example.com.tw/api/participants/


URL- http://www.example.com.tw/api/participants/1/

我們能夠透過設定權限,防止資料被任意串改,在登入的情況下才能新增/修改/刪除,其他僅能取得資料。
# app/views.py
class ParticipantViewSet(viewsets.ModelViewSet):
    queryset = Participant.objects.all()
    serializer_class = ParticipantSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly)
或是
# app/views.py
class ParticipantViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Participant.objects.all()
    serializer_class = ParticipantSerializer

URL- http://www.example.com.tw/api/api-auth/login/
右上角點選「Log in」,輸入帳密後才有修改的權限。




參考資料:
http://www.django-rest-framework.org/tutorial/quickstart/