如何构建一个API,它将为网站返回HTML,而对其他客户端返回JSON。

huangapple go评论53阅读模式
英文:

How to build API that will return HTML for the site and JSON for other clients

问题

我刚刚开始学习DRF,有一个小问题 - 如何编写一个API,该API将为我目前正在开发的网站返回HTML,并为其他“客户端”(如移动应用程序、桌面应用程序等)返回JSON格式?

我尝试搜索这方面的信息,但没有找到答案。

我唯一看到的方法是为网站创建默认的Django视图,并为其他请求创建单独的API。有人能告诉我是否我是对的,需要这样做,还是有一些代码可以解决我的问题?

英文:

I have started learning DRF just a while ago and had a little question -
how can I code one API that will return HTML for the site that I am currently working on and return JSON format for other "clients"(e.g. mobile apps, desktop, etc)?

I have tried to search for this information, but didn't found any answering content.

The only way I see is to create default Django views for the site and create separated API's for other requests. Can anybody tell me if I am right and need to do so, or there is some code that is solving my problem?

答案1

得分: 0

最终,您可以将它视为一整套独立的视图、URL,而不是模型,您需要一个序列化器。在您的应用程序中,您可以创建一个名为API的文件夹。在该目录中,您需要有一个__init__.pyurls.pyviews.py和一个serializers.py。这类似于创建标准的URL、视图、模型结构来显示HTML页面,但不包括HTML模板。还要为序列化器创建不同的URL。例如,对于登录,可以像这样做:

path('my_app_api/login', serializer_view)

如果您在YouTube上搜索"Django Rest Framework",会找到大量的视频教程。

英文:

Ultimately, you can think of it as a whole separate set of views, urls and instead of models you have a serializer. Within you're app you can create an API folder. Within that directory you will need to have an '_ _ init _ _.py', 'urls.py', 'views.py' and a 'serializers.py'. Its analogous to creating a standard url, view, model structure to display an HTML page, but without the HTML template. Make distinct urls for the serializers too. For example for login do something like this:

path('my_app_api/login', serializer_view) 

Youtube has tons of videos if you search django rest framework

huangapple
  • 本文由 发表于 2023年2月14日 02:55:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定