英文:
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__.py
,urls.py
,views.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论