This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

The Art of API Design: Lessons Learned in Building VividBlog

The outdated adage, “Measure twice, minimize as soon as,” applies completely to API design. A well-designed API is the muse for a strong and maintainable utility. On this submit, I am going to share my experiences designing the API for VividBlog, a weblog platform I just lately constructed, highlighting the significance of thorough planning and the thought processes behind key selections.

Three-Layer Cake-Construction

I at all times take API’s as a 3 layer construction

3 layer structure of API

I strategy APIs with a three-layer construction:

  • Database Layer: The rock-solid basis holding your knowledge.
  • Schema Layer: The validation gatekeeper guaranteeing knowledge integrity.
  • Endpoint Layer: The general public interface the place builders work together along with your API.

Designing for Flexibility: Database-First vs. UI-Mockup First

Whereas I tackled VividBlog’s design database-first on account of useful resource constraints, there is not any one-size-fits-all strategy. This is how to decide on the best path:

  • Database-First: Best for data-centric APIs the place knowledge integrity and construction are paramount. Assume monetary transactions or stock administration techniques.
  • UI-Mockup First: Nice for user-driven APIs the place a seamless person expertise is essential. E-commerce purposes or social media platforms profit from this strategy.

The important thing lies to find a stability. Even with out a full UI mockup, sketching core functionalities and knowledge fashions gives a worthwhile place to begin.

Within the absence of a finalized UI design, I adopted a data-centric strategy to schema design. This concerned creating separate schemas for:

  • The JSON knowledge anticipated within the request payload…
  • The JSON knowledge returned within the response payload…

Constructing the Basis: Flask-RESTful, Marshmallow and SQLAlchemy

For constructing the VividBlog API, I opted for a preferred mixture of instruments:

  • Flask-RESTful: A light-weight framework throughout the Flask ecosystem that simplifies constructing RESTful APIs in Python.
  • Marshmallow: A robust knowledge validation library that streamlines the method of guaranteeing knowledge despatched in requests adheres to the anticipated format.

This mix gives a strong and environment friendly basis for API growth.

Database Decisions: Balancing Flexibility and Construction

Whereas I initially explored SQLite for its simplicity, I in the end determined to leverage SQLAlchemy because the Object-Relational Mapper (ORM). SQLAlchemy gives a number of benefits:

  • Database Agnosticism: It permits working with numerous database backends like PostgreSQL, MySQL, or SQLite. This gives flexibility in selecting probably the most appropriate database to your undertaking’s wants.
  • Knowledge Modeling: SQLAlchemy facilitates sturdy knowledge modeling by means of its ORM capabilities, permitting you to outline knowledge buildings that intently resemble your utility objects.

Whereas SQLite gives a handy light-weight possibility, its knowledge definition strategy might be much less strict in comparison with PostgreSQL. For initiatives requiring robust knowledge integrity and sophisticated knowledge relationships, PostgreSQL typically emerges as the popular alternative.

Key Takeaway: Selecting the Proper Instruments

The selection of frameworks and databases will depend on your undertaking’s particular necessities. Think about elements like scalability, knowledge complexity, and crew familiarity when making these selections.

Assets: Modelling your API’s with Collections and Singletons

Efficient API design entails representing your knowledge fashions as sources. This part explores two key useful resource varieties:

  • Assortment Assets: Signify a group of comparable knowledge gadgets. In VividBlog, this might be a listing of all weblog posts, doubtlessly filtered by standards like class or creator.
  • Singleton Assets: Signify a single, distinctive knowledge merchandise. For VividBlog, this may be a particular weblog submit recognized by its distinctive ID.

The Energy of the Pair:

It is typically advisable to create each assortment and singleton sources for every knowledge mannequin in your API. This gives a constant and versatile option to work together along with your knowledge:

  • Assortment Assets: Best for looking, looking out, and filtering by means of a number of knowledge gadgets.
  • Singleton Assets: Good for retrieving, creating, updating, or deleting a particular knowledge merchandise.

Instance: VividBlog’s Weblog Posts

Think about VividBlog’s weblog posts saved in a database desk or relation named “weblog.” This is how these sources can be carried out:

  1. Assortment Useful resource: An endpoint like /api/v1/blogs may return a listing of all weblog posts, doubtlessly filtered by parameters like title or author_id.
  2. Singleton Useful resource: An endpoint like /api/v1/blogs/123 (the place 123 is the distinctive ID of a particular weblog submit) would return particulars about that individual submit.

Schema and Validation

Vividblog Schema

Marshmallow performs an important function in VividBlog’s API by offering knowledge validation for each incoming and outgoing knowledge. This ensures knowledge integrity and streamlines communication between the API and consumer purposes.

Separate Schemas for Distinct Functions:
I carried out two distinct Marshmallow schemas for every knowledge mannequin:

  1. Request Schema: This schema defines the anticipated construction and validation guidelines for knowledge despatched in API requests. It acts as a gatekeeper, guaranteeing solely legitimate knowledge reaches the backend logic.
  2. Response Schema: This schema dictates the format of information returned in API responses. It defines the info construction and any transformations utilized to the info earlier than serialization.

Instance: Person Administration Schemas

Think about the person mannequin in VividBlog. Listed below are the corresponding Marshmallow schemas:

  1. CreateUserSchema: This schema would seemingly embody fields for username, e mail, and password (hashed for safety). It will implement validation guidelines like required fields and e mail format.
  2. UserItemSchema: This schema may embody the person’s ID, username, e mail (if acceptable for the response context), and doubtlessly different related person knowledge. It will decide which knowledge is included within the response and the way it’s formatted.

By separating request and response schemas, you obtain clear separation of issues and guarantee knowledge validation occurs on the acceptable stage of the API interplay.

For instance schema design, let’s take a look at a simplified instance utilizing Marshmallow for person knowledge:

from marshmallow import Schema, fields

class CreateUserSchema(Schema):
  username = fields.Str(required=True)
  e mail = fields.E mail(required=True)

class UserItemSchema(Schema):
  id = fields.Integer(read_only=True)
  username = fields.Str()
  e mail = fields.E mail()
  created_at = fields.DateTime(read_only=True)
Enter fullscreen mode

Exit fullscreen mode

The CreateUserSchema validates incoming person knowledge, whereas UserItemSchema defines the response construction, excluding robotically generated fields like id and created_at.


VividBlog makes use of JSON Internet Tokens (JWTs) for person authentication. JWTs are a preferred and safe mechanism for transmitting authentication info between a consumer and a server. They provide a number of benefits:

  • Safety: JWTs are self-contained and digitally signed, making them tamper-proof and stopping unauthorized entry.
  • Statelessness: The server would not must retailer session knowledge, simplifying structure and enhancing scalability.
  • Flexibility: JWTs can encode further person info past simply authentication standing, permitting for role-based authorization.

For a deeper understanding of JWTs and their implementation, I like to recommend exploring sources devoted to JWT authentication finest practices.

Environment friendly Knowledge Navigation: Pagination and Question Parameters

VividBlog employs pagination to permit customers to navigate by means of massive datasets of weblog posts effectively. Pagination breaks down knowledge into manageable chunks (pages) that customers can navigate by means of utilizing question parameters.

The Artwork of Pagination:

Designing an efficient pagination scheme entails a number of issues:

  • Selecting the Proper Strategy: There are two important pagination methods: offset-based and cursor-based. VividBlog makes use of offset-based pagination, the place currentPage and pageSize parameters outline the start line and variety of gadgets per web page within the requested knowledge.
  • Clear and Readable URIs: I opted for camelCase question parameters (currentPage and pageSize) to boost the readability of URIs. This makes it simpler for builders to know the aim of every parameter at a look.
  • Dealing with Edge Instances: A strong pagination system ought to deal with edge circumstances like empty pages or exceeding the whole variety of gadgets. This may contain returning acceptable error messages or adjusting the requested web page quantity.

Instance: Paginating Weblog Posts

Think about a situation the place VividBlog has 50 weblog posts. This is how pagination would work:

  • A request with currentPage=1 and pageSize=10 would retrieve the primary 10 weblog posts.
  • A request with currentPage=3 and pageSize=10 would retrieve posts 21 to 30 (assuming there are at the least 30 posts).

Past Pagination: Leveraging Question Parameters

Question parameters can prolong past pagination. VividBlog may additionally enable filtering posts by parameters like title or author_id. This empowers customers to refine their search outcomes and discover the data they want shortly
By rigorously contemplating these components, you may design a pagination system that provides a clean and environment friendly person expertise whereas sustaining clear and readable URIs.

Significance of designing API’s

Past Time Saved: The Energy of Thorough Design

The time saved by meticulous design goes past just some preliminary weeks. This is how a well-designed API pays dividends in the long term:

  • Maintainability: A transparent and logical construction makes it simpler for builders to know, modify, and prolong the API as your undertaking evolves.
  • Scalability: A well-designed basis can accommodate elevated utilization with out buckling beneath strain.
  • Consistency: Builders utilizing your API will expertise a uniform and predictable interplay, streamlining growth efforts.
  • Documentation: A well-organized API with clear logic is less complicated to doc, making it extra accessible to a wider developer viewers.

What would you do otherwise?

I am at all times in search of methods to enhance my API design expertise. Should you’ve encountered comparable challenges or have insights on how I might have approached VividBlog’s design otherwise, please share your ideas within the feedback under! Participating on this dialog may help all of us construct even higher APIs sooner or later.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?