我正在關注 RESTful Flask API ( https://www.rahmanfadhil.com/flask-rest-api/ ) 的教程,它說要向某些東西發送請求。我嘗試向 Postman 發出請求,但它說 Content-Type 不是 application/json。代碼是
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_restful import Api, Resource
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
ma = Marshmallow(app)
api = Api(app)
# classes
class Post(db.Model):
post_id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50))
content = db.Column(db.String(255))
def __repr__(self):
return '<Post %s>' % self.title
class PostSchema(ma.Schema):
class Meta:
fields = ("post_id", "title", "content")
model = Post
post_schema = PostSchema()
posts_schema = PostSchema(many=True)
class PostListResource(Resource):
def get(self):
posts = Post.query.all()
return posts_schema.dump(posts)
def post(self):
new_post = Post(
title=request.json['title'],
content=request.json['content']
)
db.session.add(new_post)
db.session.commit()
return post_schema.dump(new_post)
api.add_resource(PostListResource, '/posts')
class PostResource(Resource):
def get(self, post_id):
post = Post.query.get_or_404(post_id)
return post_schema.dump(post)
api.add_resource(PostResource, '/posts/<int:post_id>')
教程說要運行
$ curl http://localhost:5000/posts \
-X POST \
-H "Content-Type: application/json" \
-d '{"title":"Post 1", "content":"Lorem ipsum"}'
我在 Powershell 中做過,但回傳錯誤:
Invoke-WebRequest : Cannot bind parameter 'Headers'. Cannot convert the "Content-Type: application/json" value of type "System.String" to type "System.Collections.IDictionary". At line:1 char:45 ... alhost:5000/posts -X POST -H "Content-Type: application/json" -d '{"t ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
你能幫我嗎?謝謝!
另外,我想知道如何從另一個程式中呼叫它。我在請求 API 中放了什么?
uj5u.com熱心網友回復:
Postman 在 Headers 中有一個內容型別欄位,請確保將其設定為 JSON
內容型別應用程式/json
您也可以在“正文”選項卡中進行設定,但 Postman 會通知您是否存在不匹配的情況。確保選擇“raw”并將以下內容粘貼到下面的視窗中:
{
"title":"Post 1",
"content":"Lorem ipsum"
}
uj5u.com熱心網友回復:
這應該可以,但我沒有可用的 POST 端點,所以我無法測驗:
$Body = @{
Title= "Post 1"
Content = "Lorem ipsum"
}
Invoke-RestMethod -Uri "http://localhost:5000/posts" -Method Post -Body ($Body | ConvertTo-Json)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459351.html
