- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - Hello World
Getting Started
The first step in creating a FastAPI app is to declare the apppcation object of FastAPI class.
from fastapi import FastAPI app = FastAPI()
This app object is the main point of interaction of the apppcation with the cpent browser. The uvicorn server uses this object to psten to cpent’s request.
The next step is to create path operation. Path is a URL which when visited by the cpent invokes visits a mapped URL to one of the HTTP methods, an associated function is to be executed. We need to bind a view function to a URL and the corresponding HTTP method. For example, the index() function corresponds to ‘/’ path with ‘get’ operation.
@app.get("/") async def root(): return {"message": "Hello World"}
The function returns a JSON response, however, it can return dict, pst, str, int, etc. It can also return Pydantic models.
Save the following code as main.py
from fastapi import FastAPI app = FastAPI() @app.get("/") async def index(): return {"message": "Hello World"}
Start the uvicorn server by mentioning the file in which the FastAPI apppcation object is instantiated.
uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [28720] INFO: Started server process [28722] INFO: Waiting for apppcation startup. INFO: Apppcation startup complete.
Open the browser and visit http://localhost:/8000. You will see the JSON response in the browser window.
Advertisements