在Flask中构建RESTful API时出错

时间:2018-10-11 13:24:07

标签: python api flask

我正在学习构建RESTful API,并且在命令行上使用curl。

curl -i -H "Content-Type:application/json" -X POST \
  -d "{"""title""":"""Read a book"""}" \
  http://localhost:5000/todo/api/v1.0/tasks

它向我显示此错误:

curl: (6) Could not resolve host: a
curl: (3) [globbing] unmatched close brace/bracket in column 6
HTTP/1.0 400 BAD REQUEST
Content-Type: text/html
Content-Length: 204
Server: Werkzeug/0.14.1 Python/3.7.0
Date: Thu, 11 Oct 2018 13:20:28 GMT

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Failed to decode JSON object: Unterminated string starting at: line 1 column 10 (char 9)</p>

3 个答案:

答案 0 :(得分:1)

这不是在命令行上转义JSON的方式。在JSON字符串周围使用单引号:

curl -X POST "https://httpbin.org/post" -H "accept: application/json"
  -H "Content-Type: application/json" \
  -d '{"foo": "bar"}'

如果必须在JSON字符串周围使用双引号,则必须对其中的双引号进行转义:

curl -X POST "https://httpbin.org/post" -H "accept: application/json" \
  -H "Content-Type: application/json" \
  -d "{\"foo\": \"bar\"}"

答案 1 :(得分:0)

@blacksilver这是我运行-v后的代码

Trying ::1...
* TCP_NODELAY set
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 5000 (#0)
> POST /todo/api/v1.0/tasks HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.61.0
> accept: application/json
>
* HTTP 1.0, assume close after body
< HTTP/1.0 400 BAD REQUEST
< Content-Type: text/html
< Content-Length: 192
< Server: Werkzeug/0.14.1 Python/3.7.0
< Date: Thu, 11 Oct 2018 13:56:11 GMT
<
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
* Closing connection 0
* Rebuilt URL to: \/
* Could not resolve host: \
* Closing connection 1
curl: (6) Could not resolve host: \

答案 2 :(得分:0)

所以我运行了以下命令,它就起作用了

curl -X POST -H“内容类型:application / json” -d“ {\” title \“:\”读一本书\“}” http://localhost:5000/todo/api/v1.0/tasks