DESIGN GOOD PRACTICES YOU CAN'T IGNORE (but you can learn in 60 seconds)
Kristijan Kralj 1. CONSISTENT NAMING
Use consistent and descriptive
names for endpoints.
For example, if you use plural nouns,
use them everywhere: /api/products /api/users 2. USE REQUEST OBJECT
Instead of passing multiple
parameters directly to an API endpoint, encapsulate them in a single object. Later, you can easily add and remove parameters. 3. ERROR LOGGING
When an endpoint produces an
exception: 1. Log the exception. 2. Use a generic error message as a response.
Why? When you display the whole
exception message, hackers can read your code like an open book.
Don’t make their job easier.
4. INPUT VALIDATION
Expecting users to send all valid data
to your API is like expecting your computer to run fast when you are in a hurry. You can't rely on that.
There are many ways to implement
input validation in ASP.NET Core. But one of the most popular is to use FluentValidation. 5. PAGINATION
Your Web API will be blazing fast when
you minimize the data you need to return. The simplest way is with paging. 6. AVOID LONG-RUNNING HTTP API REQUESTS
Long-running requests can cause
various server issues and timeouts.
For a long-running task, use
asynchronous processing: 1. Receive the request. 2. Respond by acknowledging that you have received the request. 3. Create a background task to process the request. 7. MEANINGFUL RESPONSE CODES
Use the appropriate status code for
your responses:
1xx: I’m working on it, please wait.
2xx: Here is the response you have been waiting for. 3xx: The resource you are looking for is somewhere else. 4xx: There is an error on your side. 5xx: There is an error on my side. 8. SECURITY
One of the most underrated qualities
any Web API can have is strong security measures. Why? Because failing to implement proper security can lead to: identity and data theft, financial loss, reputation damage.
Therefore, use strong authentication
and authorization measures. 9. VERSIONING
Change is the only constant in
programming.
Sooner or later, you will have to make a
change to your API endpoints. Some changes are harmless. Some can break the existing API clients.
To prevent issues like that, use
versioning. 10. CACHING
Caching is a way to store frequently
accessed data in memory.
So, the next time, you don’t need to
fetch the data from the database. Or perform time-consuming calculations.
This reduces the load on the server
and decreases response time for clients. By implementing these good practices, your Web API will be fast, reliable, and secure. Thanks for reading!
Please repost if you find this
helpful. So other devs can build well- designed Web APIs.