Understanding CORS in API

Hasan Sajedi
4 min readNov 26, 2024

Exploring CORS Significance and Implementation in DRF and FastAPI

Cross-Origin Resource Sharing (CORS) is a critical concept in web development, especially when working with APIs. CORS defines a security feature implemented by web browsers to control the behavior of web pages when they request resources from different origins (domains). In this article, we’ll delve into what CORS is, why it’s necessary, and how to implement it in two popular Python web frameworks: Django Rest Framework (DRF) and FastAPI. Additionally, we’ll discuss the potential consequences of not using CORS.

What is CORS?

CORS, or Cross-Origin Resource Sharing, is a security feature implemented by web browsers to prevent potentially malicious web pages from making unauthorized requests to a different domain. When a web page loaded from one domain attempts to make an HTTP request to a different domain (cross-origin request), the browser enforces CORS policies to protect user data and security.

The CORS mechanism is based on HTTP headers that the server and browser use to communicate and determine whether a given request should be allowed. These headers allow server-side developers to specify which domains are permitted to access their resources.

Why is CORS Necessary?

  1. Security: CORS is primarily designed to enhance web security by preventing unauthorized cross-origin requests. Without CORS, malicious websites could make unauthorized requests to sensitive resources on other domains, potentially compromising user data.
  2. Privacy: CORS helps protect user privacy by preventing websites from making unauthorized requests to third-party servers that contain user-specific data. It ensures that only trusted websites can access this data.
  3. Isolation: CORS helps isolate web applications from one another. Without it, a web application’s data could be accessed or modified by other websites.
  4. User Experience: Enforcing CORS ensures that web applications function as intended, improving the user experience. It allows legitimate cross-origin requests while blocking harmful ones.

What Happens if We Don’t Use CORS?

Failing to implement CORS can lead to various issues, including:

  1. Cross-Origin Errors: Browsers will block cross-origin requests, and JavaScript running in the browser won’t be able to access responses from different domains. This can break important functionality in your web applications.
  2. Security Vulnerabilities: Without CORS, your API may be susceptible to cross-site request forgery (CSRF) attacks, where malicious websites trick authenticated users into performing actions on your site without their consent.
  3. Data Leakage: Unauthorized cross-origin requests could lead to data leakage, where sensitive information is exposed to unauthorized parties.

Now, let’s explore how to implement CORS in two popular Python web frameworks: Django Rest Framework and FastAPI.

Implementing CORS in Django Rest Framework (DRF)

In DRF, you can use the django-cors-headers package to easily enable CORS support. Here are the steps:

  • Install django-cors-headers using pip:
pip install django-cors-headers
  • Add 'corsheaders' to your INSTALLED_APPS in your Django project settings.
  • Configure CORS settings in your project settings:
# settings.py

CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"https://yourdomain.com",
]
  • Include the CorsMiddleware in your MIDDLEWARE setting:
# settings.py

MIDDLEWARE = [
# ...
'corsheaders.middleware.CorsMiddleware',
# ...
]

With these steps, you’ve configured CORS for your DRF project, allowing cross-origin requests from specified origins.

Implementing CORS in FastAPI

FastAPI simplifies CORS implementation with built-in support. You can configure CORS in your FastAPI application using the fastapi.middleware.cors module. Here's how:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["https://yourdomain.com"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["*"],
)

In this FastAPI example, you explicitly allow certain origins, methods, and headers.

Conclusion

Cross-Origin Resource Sharing (CORS) plays a vital role in securing web applications and protecting user data. Failing to implement CORS can lead to security vulnerabilities, data leakage, and a poor user experience. In this article, we’ve explored why CORS is necessary and how to implement it in two popular Python web frameworks, Django Rest Framework and FastAPI. By understanding and correctly configuring CORS, you can ensure the security and functionality of your web applications while providing a seamless user experience.

General CORS Resources:

  1. MDN Web Docs — Cross-Origin Resource Sharing (CORS): Mozilla’s comprehensive guide on CORS.
  2. CORS in the Django documentation: Detailed information on CORS in the official Django documentation.
  3. FastAPI CORS Documentation: The official FastAPI documentation on CORS configuration.
  4. Understanding CORS — Enable CORS: A practical guide to enabling CORS in different scenarios.

Tutorials and Guides:

  1. How to Enable CORS in Django Rest Framework: A step-by-step tutorial on enabling CORS in DRF.
  2. FastAPI CORS Configuration: A FastAPI tutorial on configuring CORS for a backend deployed on Heroku.

Packages and Libraries:

  1. django-cors-headers GitHub Repository: The official GitHub repository for django-cors-headers package.
  2. FastAPI CORSMiddleware Documentation: Detailed information on using the CORSMiddleware in FastAPI.

Videos:

  1. CORS — Cross-Origin Resource Sharing in 100 seconds: A quick and informative video explaining CORS in 100 seconds.
  2. FastAPI Tutorial — CORS Middleware: A video tutorial demonstrating CORS configuration in FastAPI.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response