Skip to main content

FastAPI Tutorial for Beginners: Build Your First API with CORS and Uvicorn

 

FastAPI is amazing! You can create APIs using FastAPI very quickly. With these APIs, you can connect the backend to the frontend. You can access user data through the API and process it on a Uvicorn server. 

Here is an example of a FastAPI app you can start with

from fastapi import FastAPI

from fastapi.middleware.cors import CORSMiddleware


app = FastAPI()


# CORS setup

app.add_middleware(

    CORSMiddleware,

    allow_origins=["*"],  # Consider restricting this in production

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"],

)



# Root route

@app.get("/")

def root():

    return {"message": "Welcome to the fastAPI"}


How to Run It

Go to the project or file directory and run the command:
uvicorn main:app --reload

Output 

You will see output like this at the URL: http://localhost:8000/



In the code, we are using CORS middleware to allow connections between different platforms, such as the frontend and backend.
You can specify your frontend website in the code (e.g., www.salimwireless.com) so that the backend only processes requests coming from that domain. This is a good practice for production environments

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

app = FastAPI()

# CORS setup
app.add_middleware(
    CORSMiddleware,
    allow_origins=["www,salimwireless.com"],  # Consider restricting this in production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# Root route
@app.get("/")
def root():
    return {"message": "Welcome to the fastAPI"}

Further Reading 

  1. For more details, visit my GitHub.

People are good at skipping over material they already know!

View Related Topics to







Admin & Author: Salim

s

  Website: www.salimwireless.com
  Interests: Signal Processing, Telecommunication, 5G Technology, Present & Future Wireless Technologies, Digital Signal Processing, Computer Networks, Millimeter Wave Band Channel, Web Development
  Seeking an opportunity in the Teaching or Electronics & Telecommunication domains.
  Possess M.Tech in Electronic Communication Systems.


Contact Us

Name

Email *

Message *

Popular Posts

Antenna Gain-Combining Methods - EGC, MRC, SC, and RMSGC

📘 Overview 🧮 Equal gain combining (EGC) 🧮 Maximum ratio combining (MRC) 🧮 Selective combining (SC) 🧮 Root mean square gain combining (RMSGC) 🧮 Zero-Forcing (ZF) Combining 🧮 MATLAB Code 📚 Further Reading  There are different antenna gain-combining methods. They are as follows. 1. Equal gain combining (EGC) 2. Maximum ratio combining (MRC) 3. Selective combining (SC) 4. Root mean square gain combining (RMSGC) 5. Zero-Forcing (ZF) Combining  1. Equal gain combining method We add the correlated data streams from different antennas in the equal gain combining method. Then we multiply the resultant data with (1/(number of antennas)) For example, for two antenna gain-combining  If the received symbols are y1 and y2, then  Equal combing gain, y_egc = 0.5 * (y1 + y2) 2. Maximum ratio combining method We multiply the individual data streams with weights in the maximum ratio combining method. More weightage is multipli...

Constellation Diagrams of ASK, PSK, and FSK

📘 Overview 🧮 Simulator for constellation diagrams of ASK, FSK, and PSK 🧮 Theory 🧮 MATLAB Codes 📚 Further Reading BASK (Binary ASK) Modulation: Transmits one of two signals: 0 or -√Eb, where Eb​ is the energy per bit. These signals represent binary 0 and 1.    BFSK (Binary FSK) Modulation: Transmits one of two signals: +√Eb​ ( On the y-axis, the phase shift of 90 degrees with respect to the x-axis, which is also termed phase offset ) or √Eb (on x-axis), where Eb​ is the energy per bit. These signals represent binary 0 and 1.  BPSK (Binary PSK) Modulation: Transmits one of two signals: +√Eb​ or -√Eb (they differ by 180 degree phase shift), where Eb​ is the energy per bit. These signals represent binary 0 and 1.    Simulator for BASK, BPSK, and BFSK Constellation Diagrams SNR (dB): 15 Add A...

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...

📘 Overview of BER and SNR 🧮 Simulator for m-ary QAM and m-ary PSK 🧮 MATLAB Codes 📚 Further Reading Modulation Constellation Diagrams BER vs. SNR BER vs SNR for M-QAM, M-PSK, QPSk, BPSK, ... What is Bit Error Rate (BER)? The abbreviation BER stands for bit error rate, which indicates how many corrupted bits are received (after the demodulation process) compared to the total number of bits sent in a communication process. It is defined as,  In mathematics, BER = (number of bits received in error / total number of transmitted bits)  On the other hand, SNR refers to the signal-to-noise power ratio. For ease of calculation, we commonly convert it to dB or decibels.   What is Signal the signal-to-noise ratio (SNR)? SNR = signal power/noise power (SNR is a ratio of signal power to noise power) SNR (in dB) = 10*log(signal power / noise power) [base 10] For instance,...

Comparisons among ASK, PSK, and FSK | And the definitions of each

📘 Overview 🧮 Simulator 🧮 Noise Sensitivity, Bandwidth, Complexity, etc. 🧮 MATLAB Codes 🧮 Some Questions and Answers 📚 Further Reading Modulation ASK, FSK & PSK Constellation MATLAB Simulink MATLAB Code Comparisons among ASK, PSK, and FSK    Comparisons among ASK, PSK, and FSK   Simulator for Calculating Bandwidth of ASK, FSK, and PSK The baud rate represents the number of symbols transmitted per second. Both baud rate and bit rate are same for binary ASK, FSK, and PSK. Select Modulation Type: ASK FSK PSK Baud Rate or Bit Rate (bps): Frequency Deviation (Hz) for FSK: Calculate Bandwidth Comparison among ASK,  FSK, and PSK Performance Comparison: 1. Noise Sensitivity:    - ASK is the most sensitive to noise due to its r...

MATLAB code for BER vs SNR for M-QAM, M-PSK, QPSk, BPSK, ...

📘 Overview 🧮 Simulator for m-ary QAM and m-ary PSK 🧮 MATLAB Code for BPSK, M-ary PSK, and M-ary QAM Together 🧮 MATLAB Code for M-ary QAM 🧮 MATLAB Code for M-ary PSK 📚 Further Reading   MATLAB Script for  BER vs. SNR for M-QAM, M-PSK, QPSk, BPSK %Written by Salim Wireless %Visit www.salimwireless.com for study materials on wireless communication %or, if you want to learn how to code in MATLAB clc; clear; close all; % Parameters num_symbols = 1e5; % Number of symbols snr_db = -20:2:20; % Range of SNR values in dB % PSK and QAM orders to be tested psk_orders = [2, 4, 8, 16, 32]; qam_orders = [4, 16, 64, 256]; % Initialize BER arrays ber_psk_results = zeros(length(psk_orders), length(snr_db)); ber_qam_results = zeros(length(qam_orders), length(snr_db)); % BER calculation for each PSK order and SNR value for i = 1:length(psk_orders) psk_order = psk_orders(i); for j = 1:length(snr_db) % Generate random symbols ...

MATLAB Code for Pulse Amplitude Modulation (PAM) and Demodulation

📘 Overview & Theory 🧮 MATLAB Code 1 🧮 MATLAB Code 2 🧮 MATLAB Code for Pulse Amplitude Modulation and Demodulation of Digital data 🧮 Other Pulse Modulation Techniques (e.g., PWM, PPM, DM, and PCM) 📚 Further Reading   Pulse Amplitude Modulation (PAM) & Demodulation MATLAB Script clc; clear all; close all; fm= 10; % frequency of the message signal fc= 100; % frequency of the carrier signal fs=1000*fm; % (=100KHz) sampling frequency (where 1000 is the upsampling factor) t=0:1/fs:1; % sampling rate of (1/fs = 100 kHz) m=1*cos(2*pi*fm*t); % Message signal with period 2*pi*fm (sinusoidal wave signal) c=0.5*square(2*pi*fc*t)+0.5; % square wave with period 2*pi*fc s=m.*c; % modulated signal (multiplication of element by element) subplot(4,1,1); plot(t,m); title('Message signal'); xlabel ('Time'); ylabel('Amplitude'); subplot(4,1,2); plot(t,c); title('Carrier signal'); xlabel('Time'); ylabel('Amplitu...

Constellation Diagram of FSK in Detail

  Binary bits '0' and '1' can be mapped to 'j' and '1' to '1', respectively, for Baseband Binary Frequency Shift Keying (BFSK) . Signals are in phase here. These bits can be mapped into baseband representation for a number of uses, including power spectral density (PSD) calculations. For passband BFSK transmission, we can modulate signal 'j' with a lower carrier frequency and signal '1' with a higher carrier frequency while transmitting over a wireless channel. Let's assume we are transmitting carrier signal fc1 for the transmission of binary bit '1' and carrier signal fc2 for the transmission of binary bit '0'. Simulator for 2-FSK Constellation Diagram Simulator for 2-FSK Constellation Diagram SNR (dB): 15 Add AWGN Noise Run Simulation ...