Skip to content
Advertisement

Django Rest API from Database

I have 2 APIs from my existing project. Where One provides the latest blog posts and another one provides sorting details. The 2nd API (sorting) gives blog posts ID and an ordering number, which should be in the 1st,2nd,3rd…n position. If I filter in the first API with that given ID I can get the blog post details.

How can I create a Django REST API from Database? or an API merging from that 2 APIs? Any tutorial or reference which might help me?

Frist API Response:

{
  "count": 74,
  "next": "https://cms.example.com/api/v2/stories/?page=2",
  "previous": null,
  "results": [
    {
      "id": 111,
      "meta": {
        "type": "blog.CreateStory",
        "seo_title": "",
        "search_description": "",
        "first_published_at": "2022-10-09T07:29:17.029746Z"
      },
      "title": "A Test Blog Post"
},
{
      "id": 105,
      "meta": {
        "type": "blog.CreateStory",
        "seo_title": "",
        "search_description": "",
        "first_published_at": "2022-10-08T04:45:32.165072Z"
      },
      "title": "Blog Story 2"
},

2nd API Response

[
  {
    "featured_item": 1,
    "sort_order": 0,
    "featured_page": 105
  },
  {
    "featured_item": 1,
    "sort_order": 1,
    "featured_page": 90
  },

Here I want to create another API that will provide more details about sorting for example it will sort like this https://cms.example.com/api/v2/stories/105 and catch Title, Image & Excerpt and If there is no data from Sorting details it will show the first API’s response by default.

Advertisement

Answer

After searching, I found that you can make API from Database. In setting you need to set the database credentials and then need to create a class inside your models.py and inside class’s meta you need to set meta name to db_table and then create serializers.py and views.py as you create REST API.

class SortAPI(models.Model):
    featured_item_id = models.IntegerField()
    sort_order = models.IntegerField()
    title=models.TextField()
    first_published_at=models.DateTimeField()
    alternative_title= models.TextField()
    excerpt=models.TextField()
    sub_heading=models.TextField()
    news_slug=models.TextField()
    img_title=models.TextField()
    img_url=models.TextField()
    img_width=models.IntegerField()
    img_height=models.IntegerField()

    class Meta:
        db_table = 'view_featured'
Advertisement