DeveloperBreeze

Python Code Snippet: Simple RESTful API with FastAPI

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Book(BaseModel):
    title: str
    author: str

# Sample data
books_db = [
    Book(title="The Catcher in the Rye", author="J.D. Salinger"),
    Book(title="To Kill a Mockingbird", author="Harper Lee"),
    Book(title="1984", author="George Orwell")
]

@app.get("/books/", response_model=List[Book])
async def get_books():
    return books_db

@app.post("/books/", response_model=Book)
async def add_book(book: Book):
    books_db.append(book)
    return book

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Related Posts

More content you might like

Tutorial
javascript python

How to Build a Fullstack App with Flask and React

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    // Fetch data from the Flask API
    axios.get('http://127.0.0.1:5000/')
      .then(response => setMessage(response.data.message))
      .catch(error => console.log(error));
  }, []);

  return (
    <div className="App">
      <h1>{message}</h1>
    </div>
  );
}

export default App;

To fetch data from the Flask backend, install Axios in the React frontend:

Sep 30, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

التعامل مع JSON هو جزء أساسي من تطوير تطبيقات الويب الحديثة. سواء كنت تحتاج إلى جلب البيانات من API أو كتابة بيانات إلى خادم، فإن فهم كيفية قراءة وكتابة JSON سيساعدك في بناء تطبيقات قوية وقابلة للتوسيع.

من خلال هذا الدليل، تعلمنا كيفية تحويل الكائنات إلى JSON باستخدام JSON.stringify()، وكيفية قراءة بيانات JSON باستخدام JSON.parse()، وكذلك كيفية جلب البيانات من API والتعامل مع JSON المعقد.

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

While AJAX originally stood for "Asynchronous JavaScript and XML," JSON has become the most commonly used data format over XML.

When a user performs an action on the page, like clicking a button, JavaScript can send a request to a server, receive data, and update the page content without reloading the whole page.

Sep 18, 2024
Read More
Tutorial
python

Getting Started with Pydantic: Data Validation and Type Coercion in Python

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    name: str
    age: int

@app.post("/users/")
async def create_user(user: User):
    return user

FastAPI will automatically validate the incoming request data against the User model.

Aug 29, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!