D-8. Rails 用Postman测试自己的WEB API && Valid Parentheses

请先安装Postman
今天完成整个CRUD,简单介绍操作Postman


接续昨天文章

9.修改routes.rbarticles_controller.rb

articles_controller.rb

class Api::V1::ArticlesController < ApplicationController
  before_action :find_article, only: [:show, :update, :destroy]
end

routes.rb

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :articles
    end
  end
end

10.把articles_controller.rb剩下功能补足。

一样直接把最後的code秀出,真的就是一般的CRUD

class Api::V1::ArticlesController < ApplicationController
  before_action :find_article, only: [:show, :update, :destroy]

  #GET
  def index
    @articles = Article.all
    render json:@articles, status: 200
  end

  #GET
  def show
    begin @article
      render json: @article, status: 200
    rescue
      render json: {error: "article not found!"}
    end
  end

  #POST
  def create
    @article = Article.new(article_params)
      if @article.save
        render json: @article, status: 200
      else
        render json: {erroe: "create failed"}
      end
  end

  #PATCH
  def update
    if @article.update(article_params)
      render json: @article, status: 200
    else
      render json: {erroe: "update failed"}
    end
  end

  #DELETE
  def destroy
    @article.destroy
  end

  private
  def find_article
    @article = Article.find(params[:id])
  end

  def article_params
    parmas.requir(:article).permit([
      :title,
      :author,
      :description
    ])
  end
end

甚至比一般CRUD要写的还更少??!!

为何没有newedit?
其实CRUD就是答案,在没有GUI(图形介面)的状况下newedit也失去意义,只要能正确就好。


11.帮Artcile加上一些简单验证。

至少不允许空白。
app/modles/article.rb

class Article < ApplicationRecord
  validates :title, presence: true
  validates :author, presence: true
  validates :description, presence: true
end

12.使用postman操作。

可以进设定改Themes,白的看久会瞎,黑的看久会累。

GET

Postman用途很多,这边只简单介绍测试CRUD部分是否正常。
rails s後开启postman後请点选蓝色框中的+
https://ithelp.ithome.com.tw/upload/images/20210922/20135887xIqSvyqX01.png


GET:於蓝色框贴上API首页网址,示范中的是http://localhost:3000//api/v1/articles
https://ithelp.ithome.com.tw/upload/images/20210922/201358874ReXT9XeYE.png


点选Send後,正确会看到类似下面的画面。
https://ithelp.ithome.com.tw/upload/images/20210922/20135887xOKhvebMSw.png

也可以把网址改成http://localhost:3000//api/v1/articles/2,确认show是否也正常。


POST

可以点一次+开启一个新个工作画面,或直接将GET改选为POST
https://ithelp.ithome.com.tw/upload/images/20210922/20135887LzV7Dhao8x.png


建立HeadBody
蓝色框框为预设隐藏的Head,也可点开看看。
红色框框点选後即可输入资料,KEY请输入Content-TypeVALUE请输入application/json,软件预设打头几个字後,会跳出选项选择。
https://ithelp.ithome.com.tw/upload/images/20210922/20135887XuVJ5WUoAc.png

若不清楚这一步的意思,简单说明为,Header为让API知道我们传出的资讯内容是哪种类型(media type),需要输入KEYVALUE,由这两个知道我们要传送的内容为json资料。


接着输入Body。请点选如蓝色框的raw,红色框会自动跳出,我们要输入JSON就不用改选其他了。
https://ithelp.ithome.com.tw/upload/images/20210922/201358874FEy3enkNx.png


目前Postman预设如果发现语法错误,会出现红色底线也会跳出建议更改的选项。
https://ithelp.ithome.com.tw/upload/images/20210922/20135887bRlgPoAX5D.png

输入好内容後,就可以点Send送出了。
可以一行处理,有错误如上面所叙,Postman会提醒。

{ "article" : {"title" : "练习使用Postman", "author" : "nauosika", "description" : "其实,JSON的格式,一开始有点难掌握...." }}

如果画面中原本的Response区出现类似以下画面,代表已成功完成新增,也可回游览器确认。
https://ithelp.ithome.com.tw/upload/images/20210922/20135887eeBYNwnmlM.png


PATCH

输入show的网址,这边便以http://localhost:3000//api/v1/articles/1来做测试,与POST相同,将Header完成(内容相同),Body部分将原本的articles/1内容稍做修改,Send後可以顺利可以看到Response的回馈。
https://ithelp.ithome.com.tw/upload/images/20210922/20135887Slbu0hKsXn.png

回自己浏览器会发现"id":1的内容也有确实改变。


DELETE

+DELETE输入网址,我以articles/10做测试。
不用设定HeaderBody,确定这笔资料不要了就按Send吧。
https://ithelp.ithome.com.tw/upload/images/20210922/201358871kRfie1JfV.png


由於没设定要回传什麽,但是可以发现status由200变204,内容也说明确实完成请求。
https://ithelp.ithome.com.tw/upload/images/20210922/20135887O5tnRbFhw2.png


有需求也可以对controller改写。

def destroy
    @article.destroy
    render json: {message: "DELETE Done!"}
  end

这样删除後,Postman就会有回传内容了。
https://ithelp.ithome.com.tw/upload/images/20210922/20135887Yn2vOljIXE.png


OK!

一个简单的web api已经制作完成了,明天就是建立验证机制了。


今天的leetcode.20. Valid Parentheses
题目连结:https://leetcode.com/problems/valid-parentheses/
题目重点:查表法,或是开新阵列,将元素放进去比对都行。

# @param {String} s
# @return {Boolean}
def is_valid(s)

end

puts is_valid("()")  #=> true
puts is_valid("()[]{}")  #=> true
puts is_valid("([)]")  #=> false
puts is_valid("{[]}")  #=> true

用新阵列解。
用三个例子就看得出规律了。
遇到([{就把它丢进空阵列。

when '(', '[', `}`
  new_array.push

遇到)]}就把有已经有东西的空阵列pop最後一个值出来。

when ')'
  false if new_array.pop != '('

"{[]}"这个例子也不用担心因为{[已经都丢进去了。

def is_valid(s)
  return true if s.empty? #这个是submit後发现有""这个例子。
  arr = []
  s.each_char do |char|
    case char
    when "(", "[", "{"
      arr << char
    when ")"
      return false if arr.pop != "("
    when "]"
      return false if arr.pop != "["
    when "}"
      return false if arr.pop != "{"
    end
  end
  arr.empty?
end

查表法不说明了。

def is_valid(s)
  arr = []
  hash = { '{' => '}', '[' => ']', '(' => ')' }
  s.each_char do |char|
    if hash.has_key?(char)
      arr << char
    else
      return false if arr.pop != hash.key(char)
    end
  end
  arr.empty?
end

<<:  【把玩Azure DevOps】Day10 CI/CD从这里:第2个Pipeline,建立共用的Build Pipeline

>>:  Day-10 近水楼台先得月

[day-13] Python 内建的数值类函式

Python 内建的数值类函式 数值类函式 执行结果 功能 abs(-10) 10 取绝对值 min...

Day 6. 资料库篇

後端工程师最必须要会的其中一个技能,就是对资料库的操作,我相信很少有後端工程师可以完全不用学到对资料...

Day 29:神奇语法糖-v-model

整个系列都快要完结篇了,怎麽可能独漏 Vue 的神奇语法糖—— v-model 呢?我们已经知道 V...

Vue.js 从零开始:v-bind

这篇终於要开始学习指令,先从v-bind开始介绍,单纯用JavaScript来控制的属性,需要写蛮多...

DES-EDE3-CBC

初始化向量(IV)是一个随机数,通常是一次使用的数字,即一个随机数。它用於删除密文中的重复模式,以增...