First Steps - FastAPI (2024)

The simplest FastAPI file could look like this:

from fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}

Copy that to a file main.py.

Run the live server:

$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:single">main.py</u><font color="#3465A4">INFO </font> Using path <font color="#3465A4">main.py</font><font color="#3465A4">INFO </font> Resolved absolute path <font color="#75507B">/home/user/code/awesomeapp/</font><font color="#AD7FA8">main.py</font><font color="#3465A4">INFO </font> Searching for package file structure from directories with <font color="#3465A4">__init__.py</font> files<font color="#3465A4">INFO </font> Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font> ╭─ <font color="#8AE234"><b>Python module file</b></font> ─╮ │ │ │ 🐍 main.py │ │ │ ╰──────────────────────╯<font color="#3465A4">INFO </font> Importing module <font color="#4E9A06">main</font><font color="#3465A4">INFO </font> Found importable FastAPI app ╭─ <font color="#8AE234"><b>Importable FastAPI app</b></font> ─╮ │ │ │ <span style="background-color:#272822"><font color="#FF4689">from</font></span><span style="background-color:#272822"><font color="#F8F8F2"> main </font></span><span style="background-color:#272822"><font color="#FF4689">import</font></span><span style="background-color:#272822"><font color="#F8F8F2"> app</font></span><span style="background-color:#272822"> </span> │ │ │ ╰──────────────────────────╯<font color="#3465A4">INFO </font> Using import string <font color="#8AE234"><b>main:app</b></font> <span style="background-color:#C4A000"><font color="#2E3436">╭────────── FastAPI CLI - Development mode ───────────╮</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ Serving at: http://127.0.0.1:8000 │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ API docs: http://127.0.0.1:8000/docs │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ Running in development mode, for production use: │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ </font></span><span style="background-color:#C4A000"><font color="#555753"><b>fastapi run</b></font></span><span style="background-color:#C4A000"><font color="#2E3436"> │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">│ │</font></span> <span style="background-color:#C4A000"><font color="#2E3436">╰─────────────────────────────────────────────────────╯</font></span><font color="#4E9A06">INFO</font>: Will watch for changes in these directories: [&apos;/home/user/code/awesomeapp&apos;]<font color="#4E9A06">INFO</font>: Uvicorn running on <b>http://127.0.0.1:8000</b> (Press CTRL+C to quit)<font color="#4E9A06">INFO</font>: Started reloader process [<font color="#34E2E2"><b>2265862</b></font>] using <font color="#34E2E2"><b>WatchFiles</b></font><font color="#4E9A06">INFO</font>: Started server process [<font color="#06989A">2265873</font>]<font color="#4E9A06">INFO</font>: Waiting for application startup.<font color="#4E9A06">INFO</font>: Application startup complete.

In the output, there's a line with something like:

INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

That line shows the URL where your app is being served, in your local machine.

Check it

Open your browser at http://127.0.0.1:8000.

You will see the JSON response as:

{"message": "Hello World"}

Interactive API docs

Now go to http://127.0.0.1:8000/docs.

You will see the automatic interactive API documentation (provided by Swagger UI):

First Steps - FastAPI (1)

Alternative API docs

And now, go to http://127.0.0.1:8000/redoc.

You will see the alternative automatic documentation (provided by ReDoc):

First Steps - FastAPI (2)

OpenAPI

FastAPI generates a "schema" with all your API using the OpenAPI standard for defining APIs.

"Schema"

A "schema" is a definition or description of something. Not the code that implements it, but just an abstract description.

API "schema"

In this case, OpenAPI is a specification that dictates how to define a schema of your API.

This schema definition includes your API paths, the possible parameters they take, etc.

Data "schema"

The term "schema" might also refer to the shape of some data, like a JSON content.

In that case, it would mean the JSON attributes, and data types they have, etc.

OpenAPI and JSON Schema

OpenAPI defines an API schema for your API. And that schema includes definitions (or "schemas") of the data sent and received by your API using JSON Schema, the standard for JSON data schemas.

Check the openapi.json

If you are curious about how the raw OpenAPI schema looks like, FastAPI automatically generates a JSON (schema) with the descriptions of all your API.

You can see it directly at: http://127.0.0.1:8000/openapi.json.

It will show a JSON starting with something like:

{ "openapi": "3.1.0", "info": { "title": "FastAPI", "version": "0.1.0" }, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": { "application/json": {...

What is OpenAPI for

The OpenAPI schema is what powers the two interactive documentation systems included.

And there are dozens of alternatives, all based on OpenAPI. You could easily add any of those alternatives to your application built with FastAPI.

You could also use it to generate code automatically, for clients that communicate with your API. For example, frontend, mobile or IoT applications.

Recap, step by step

Step 1: import FastAPI

from fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}

FastAPI is a Python class that provides all the functionality for your API.

"Technical Details"

FastAPI is a class that inherits directly from Starlette.

You can use all the Starlette functionality with FastAPI too.

Step 2: create a FastAPI "instance"

from fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}

Here the app variable will be an "instance" of the class FastAPI.

This will be the main point of interaction to create all your API.

Step 3: create a path operation

Path

"Path" here refers to the last part of the URL starting from the first /.

So, in a URL like:

https://example.com/items/foo

...the path would be:

/items/foo

Info

A "path" is also commonly called an "endpoint" or a "route".

While building an API, the "path" is the main way to separate "concerns" and "resources".

Operation

"Operation" here refers to one of the HTTP "methods".

One of:

  • POST
  • GET
  • PUT
  • DELETE

...and the more exotic ones:

  • OPTIONS
  • HEAD
  • PATCH
  • TRACE

In the HTTP protocol, you can communicate to each path using one (or more) of these "methods".

When building APIs, you normally use these specific HTTP methods to perform a specific action.

Normally you use:

  • POST: to create data.
  • GET: to read data.
  • PUT: to update data.
  • DELETE: to delete data.

So, in OpenAPI, each of the HTTP methods is called an "operation".

We are going to call them "operations" too.

Define a path operation decorator

from fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}

The @app.get("/") tells FastAPI that the function right below is in charge of handling requests that go to:

  • the path /
  • using a get operation

"@decorator Info"

That @something syntax in Python is called a "decorator".

You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).

A "decorator" takes the function below and does something with it.

In our case, this decorator tells FastAPI that the function below corresponds to the path / with an operation get.

It is the "path operation decorator".

You can also use the other operations:

  • @app.post()
  • @app.put()
  • @app.delete()

And the more exotic ones:

  • @app.options()
  • @app.head()
  • @app.patch()
  • @app.trace()

Tip

You are free to use each operation (HTTP method) as you wish.

FastAPI doesn't enforce any specific meaning.

The information here is presented as a guideline, not a requirement.

For example, when using GraphQL you normally perform all the actions using only POST operations.

Step 4: define the path operation function

This is our "path operation function":

  • path: is /.
  • operation: is get.
  • function: is the function below the "decorator" (below @app.get("/")).
from fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}

This is a Python function.

It will be called by FastAPI whenever it receives a request to the URL "/" using a GET operation.

In this case, it is an async function.

You could also define it as a normal function instead of async def:

from fastapi import FastAPIapp = FastAPI()@app.get("/")def root(): return {"message": "Hello World"}

Note

If you don't know the difference, check the Async: "In a hurry?".

Step 5: return the content

from fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}

You can return a dict, list, singular values as str, int, etc.

You can also return Pydantic models (you'll see more about that later).

There are many other objects and models that will be automatically converted to JSON (including ORMs, etc). Try using your favorite ones, it's highly probable that they are already supported.

Recap

  • Import FastAPI.
  • Create an app instance.
  • Write a path operation decorator using decorators like @app.get("/").
  • Define a path operation function; for example, def root(): ....
  • Run the development server using the command fastapi dev.
First Steps - FastAPI (2024)
Top Articles
CreditSesame.com Review - Is It Safe Or Is It A Scam?
Why Do Travel Nurses Get Paid So Much? - NurseJournal.org
Palm Coast Permits Online
Satyaprem Ki Katha review: Kartik Aaryan, Kiara Advani shine in this pure love story on a sensitive subject
Trabestis En Beaumont
T Mobile Rival Crossword Clue
30 Insanely Useful Websites You Probably Don't Know About
Usborne Links
Beacon Schnider
Aces Fmc Charting
Okatee River Farms
Meg 2: The Trench Showtimes Near Phoenix Theatres Laurel Park
New Day Usa Blonde Spokeswoman 2022
Craigslist Chautauqua Ny
454 Cu In Liters
Bestellung Ahrefs
Jack Daniels Pop Tarts
FAQ: Pressure-Treated Wood
Dutchess Cleaners Boardman Ohio
Alexandria Van Starrenburg
24 Hour Drive Thru Car Wash Near Me
Rural King Credit Card Minimum Credit Score
All Obituaries | Verkuilen-Van Deurzen Family Funeral Home | Little Chute WI funeral home and cremation
Utexas Iot Wifi
Wat is een hickmann?
Watertown Ford Quick Lane
Joann Fabrics Lexington Sc
Mami No 1 Ott
Pay Stub Portal
Mastering Serpentine Belt Replacement: A Step-by-Step Guide | The Motor Guy
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
Craigslist In Myrtle Beach
Mississippi State baseball vs Virginia score, highlights: Bulldogs crumble in the ninth, season ends in NCAA regional
Why Holly Gibney Is One of TV's Best Protagonists
D3 Boards
Regis Sectional Havertys
Heelyqutii
The Thing About ‘Dateline’
Anya Banerjee Feet
What Does Code 898 Mean On Irs Transcript
Barber Gym Quantico Hours
Beaufort SC Mugshots
Luvsquad-Links
Sams Gas Price Sanford Fl
Mudfin Village Wow
Divinity: Original Sin II - How to Use the Conjurer Class
Bustednewspaper.com Rockbridge County Va
Euro area international trade in goods surplus €21.2 bn
Guy Ritchie's The Covenant Showtimes Near Look Cinemas Redlands
Craigslist Com Brooklyn
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6023

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.