prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
est = require('supertest') describe('req', function(){ describe('.range(size)', function(){ it('should return parsed ranges', function (done) { var app = express() app.use(function (req, res) { res.json(req.range(120)) }) request(app) .get('/') .set('Range', 'bytes=0...
e when open-ended', function (done) { var app = express() app.use(function (req, res) { res.json(req.range(75)) }) request(app) .get('/') .set('Range', 'bytes=0-') .expect(200, '[{"start":0,"end":74}]', d
(function (req, res) { res.json(req.range(75)) }) request(app) .get('/') .set('Range', 'bytes=0-100') .expect(200, '[{"start":0,"end":74}]', done) }) it('should cap to the given siz
{ "filepath": "test/req.range.js", "language": "javascript", "file_size": 2351, "cut_index": 563, "middle_length": 229 }
express = require('../') , request = require('supertest') , cookieParser = require('cookie-parser') describe('req', function(){ describe('.signedCookies', function(){ it('should return a signed JSON cookie', function(done){ var app = express(); app.use(cookieParser('secret')); app.use(fu...
'/set') .end(function(err, res){ if (err) return done(err); var cookie = res.header['set-cookie']; request(app) .get('/') .set('Cookie', cookie) .expect(200, { obj: { foo: 'bar' } }, done) });
} }); request(app) .get(
{ "filepath": "test/req.signedCookies.js", "language": "javascript", "file_size": 851, "cut_index": 529, "middle_length": 52 }
ar express = require('../') , request = require('supertest'); describe('req', function(){ describe('.query', function(){ it('should default to {}', function(done){ var app = createApp(); request(app) .get('/') .expect(200, '{}', done); }); it('should default to parse simple ke...
200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done); }); it('should parse parameters with dots', function (done) { var app = createApp('extended'); request(app) .get('/?user.name=tj') .expect(200, '{"us
" is extended', function () { it('should parse complex keys', function (done) { var app = createApp('extended'); request(app) .get('/?foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!') .expect(
{ "filepath": "test/req.query.js", "language": "javascript", "file_size": 2703, "cut_index": 563, "middle_length": 229 }
e strict' var express = require('../') , request = require('supertest'); describe('req', function(){ describe('.stale', function(){ it('should return false when the resource is not modified', function(done){ var app = express(); var etag = '"12345"'; app.use(function(req, res){ res....
f-None-Match', '"12345"') .expect(200, 'true', done); }) it('should return true without response headers', function(done){ var app = express(); app.disable('x-powered-by') app.use(function(req, res){ res.send(req.s
n the resource is modified', function(done){ var app = express(); app.use(function(req, res){ res.set('ETag', '"123"'); res.send(req.stale); }); request(app) .get('/') .set('I
{ "filepath": "test/req.stale.js", "language": "javascript", "file_size": 1102, "cut_index": 515, "middle_length": 229 }
est = require('supertest'); describe('req', function(){ describe('.secure', function(){ describe('when X-Forwarded-Proto is missing', function(){ it('should return false when http', function(done){ var app = express(); app.get('/', function(req, res){ res.send(req.secure ? 'yes' ...
.get('/') .set('X-Forwarded-Proto', 'https') .expect('no', done) }) it('should return true when "trust proxy" is enabled', function(done){ var app = express(); app.enable('trust proxy'); app.get('/
', function(){ it('should return false when http', function(done){ var app = express(); app.get('/', function(req, res){ res.send(req.secure ? 'yes' : 'no'); }); request(app)
{ "filepath": "test/req.secure.js", "language": "javascript", "file_size": 2457, "cut_index": 563, "middle_length": 229 }
use strict' var express = require('../') , request = require('supertest'); describe('req', function(){ describe('.xhr', function(){ before(function () { this.app = express() this.app.get('/', function (req, res) { res.send(req.xhr) }) }) it('should return true when X-Request...
request(this.app) .get('/') .set('X-Requested-With', 'blahblah') .expect(200, 'false', done) }) it('should return false when not present', function(done){ request(this.app) .get('/') .expect(200
ld case-insensitive', function(done){ request(this.app) .get('/') .set('X-Requested-With', 'XMLHttpRequest') .expect(200, 'true', done) }) it('should return false otherwise', function(done){
{ "filepath": "test/req.xhr.js", "language": "javascript", "file_size": 1030, "cut_index": 513, "middle_length": 229 }
fer } = require('node:buffer'); var express = require('../') , request = require('supertest'); describe('res', function(){ describe('.attachment()', function(){ it('should Content-Disposition to attachment', function(done){ var app = express(); app.use(function(req, res){ res.attachment()...
expect('Content-Disposition', 'attachment; filename="image.png"', done); }) it('should set the Content-Type', function(done){ var app = express(); app.use(function(req, res){ res.attachment('/path/to/image.png'); res.s
d add the filename param', function(done){ var app = express(); app.use(function(req, res){ res.attachment('/path/to/image.png'); res.send('foo'); }); request(app) .get('/') .
{ "filepath": "test/res.attachment.js", "language": "javascript", "file_size": 1948, "cut_index": 537, "middle_length": 229 }
t('should generate a JSON cookie', function(done){ var app = express(); app.use(function(req, res){ res.cookie('user', { name: 'tobi' }).end(); }); request(app) .get('/') .expect('Set-Cookie', 'user=j%3A%7B%22name%22%3A%22tobi%22%7D; Path=/') .expect(200, done) })...
app.use(function(req, res){ res.cookie('name', 'tobi'); res.cookie('age', 1); res.cookie('gender', '?'); res.end(); }); request(app) .get('/') .expect('Set-Cookie', 'name=tobi; Path=/,age=1; Path
obi').end(); }); request(app) .get('/') .expect('Set-Cookie', 'name=tobi; Path=/') .expect(200, done) }) it('should allow multiple calls', function(done){ var app = express();
{ "filepath": "test/res.cookie.js", "language": "javascript", "file_size": 7428, "cut_index": 716, "middle_length": 229 }
res.format({ 'text/plain': function(){ res.send('hey'); }, 'text/html': function(){ res.send('<p>hey</p>'); }, 'application/json': function(a, b, c){ assert(req === a) assert(res === b) assert(next === c) res.send({ message: 'hey' }); } }); }); app1.use(...
tatus) res.send('Supports: ' + err.types.join(', ')) }) var app3 = express(); app3.use(function(req, res, next){ res.format({ text: function(){ res.send('hey') }, default: function (a, b, c) { assert(req === a) assert(res === b)
){ res.format({ text: function(){ res.send('hey') }, html: function(){ res.send('<p>hey</p>') }, json: function(){ res.send({ message: 'hey' }) } }); }); app2.use(function(err, req, res, next){ res.status(err.s
{ "filepath": "test/res.format.js", "language": "javascript", "file_size": 5901, "cut_index": 716, "middle_length": 229 }
bject)', function(){ it('should respond with jsonp', function(done){ var app = express(); app.use(function(req, res){ res.jsonp({ count: 1 }); }); request(app) .get('/?callback=something') .expect('Content-Type', 'text/javascript; charset=utf-8') .expect(200, /som...
}) it('should ignore object callback parameter with jsonp', function(done){ var app = express(); app.use(function(req, res){ res.jsonp({ count: 1 }); }); request(app) .get('/?callback[a]=something') .exp
np({ count: 1 }); }); request(app) .get('/?callback=something&callback=somethingelse') .expect('Content-Type', 'text/javascript; charset=utf-8') .expect(200, /something\(\{"count":1\}\);/, done);
{ "filepath": "test/res.jsonp.js", "language": "javascript", "file_size": 9154, "cut_index": 716, "middle_length": 229 }
on(){ describe('.subdomains', function(){ describe('when present', function(){ it('should return an array', function(done){ var app = express(); app.use(function(req, res){ res.send(req.subdomains); }); request(app) .get('/') .set('Host', 'tobi.fer...
){ var app = express(); app.use(function(req, res){ res.send(req.subdomains); }); request(app) .get('/') .set('Host', '[::1]') .expect(200, [], done); }) }) describe('otherw
eq, res){ res.send(req.subdomains); }); request(app) .get('/') .set('Host', '127.0.0.1') .expect(200, [], done); }) it('should work with IPv6 address', function(done
{ "filepath": "test/req.subdomains.js", "language": "javascript", "file_size": 4328, "cut_index": 614, "middle_length": 229 }
= require('../') , request = require('supertest'); describe('res', function(){ describe('.clearCookie(name)', function(){ it('should set a cookie passed expiry', function(done){ var app = express(); app.use(function(req, res){ res.clearCookie('sid').end(); }); request(app) ...
t('Set-Cookie', 'sid=; Path=/admin; Expires=Thu, 01 Jan 1970 00:00:00 GMT') .expect(200, done) }) it('should ignore maxAge', function(done){ var app = express(); app.use(function(req, res){ res.clearCookie('sid', { path:
it('should set the given params', function(done){ var app = express(); app.use(function(req, res){ res.clearCookie('sid', { path: '/admin' }).end(); }); request(app) .get('/') .expec
{ "filepath": "test/res.clearCookie.js", "language": "javascript", "file_size": 1606, "cut_index": 537, "middle_length": 229 }
de:assert'); describe('res', function(){ describe('.json(object)', function(){ it('should not support jsonp callbacks', function(done){ var app = express(); app.use(function(req, res){ res.json({ foo: 'bar' }); }); request(app) .get('/?callback=foo') .expect('{"foo":...
}) describe('when given primitives', function(){ it('should respond with json for null', function(done){ var app = express(); app.use(function(req, res){ res.json(null); }); request(app) .get(
d.example+json'); res.json({ hello: 'world' }); }); request(app) .get('/') .expect('Content-Type', 'application/vnd.example+json; charset=utf-8') .expect(200, '{"hello":"world"}', done);
{ "filepath": "test/res.json.js", "language": "javascript", "file_size": 4812, "cut_index": 614, "middle_length": 229 }
(){ describe('.download(path)', function(){ it('should transfer as an attachment', function(done){ var app = express(); app.use(function(req, res){ res.download('test/fixtures/user.html'); }); request(app) .get('/') .expect('Content-Type', 'text/html; charset=utf-8') ...
er.name}}</p>', done) }) it('should respond with requested byte range', function (done) { var app = express() app.get('/', function (req, res) { res.download('test/fixtures/user.html') }) request(app) .get
var app = express() app.get('/', function (req, res) { res.download('test/fixtures/user.html') }) request(app) .get('/') .expect('Accept-Ranges', 'bytes') .expect(200, '<p>{{us
{ "filepath": "test/res.download.js", "language": "javascript", "file_size": 13140, "cut_index": 921, "middle_length": 229 }
ar express = require('..') var request = require('supertest') describe('res', function () { describe('.append(field, val)', function () { it('should append multiple headers', function (done) { var app = express() app.use(function (req, res, next) { res.append('Set-Cookie', 'foo=bar') ...
res.append('Set-Cookie', ['foo=bar', 'fizz=buzz']) res.end() }) request(app) .get('/') .expect(200) .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar', 'fizz=buzz'])) .end(done) }) i
.expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar', 'fizz=buzz'])) .end(done) }) it('should accept array of values', function (done) { var app = express() app.use(function (req, res, next) {
{ "filepath": "test/res.append.js", "language": "javascript", "file_size": 2925, "cut_index": 563, "middle_length": 229 }
default to a 302 redirect', function(done){ var app = express(); app.use(function(req, res){ res.redirect('http://google.com'); }); request(app) .get('/') .expect('location', 'http://google.com') .expect(302, done) }) it('should encode "url"', function (done)...
res.redirect('https://google.com?q=%A710') }) request(app) .get('/') .expect('Location', 'https://google.com?q=%A710') .expect(302, done) }) }) describe('.redirect(status, url)', function(){ it('should set the r
'https://google.com?q=%E2%98%83%20%C2%A710') .expect(302, done) }) it('should not touch already-encoded sequences in "url"', function (done) { var app = express() app.use(function (req, res) {
{ "filepath": "test/res.redirect.js", "language": "javascript", "file_size": 6121, "cut_index": 716, "middle_length": 229 }
ction(done){ var app = express(); app.use(function(req, res){ res.send(); }); request(app) .get('/') .expect(200, '', done); }) }) describe('.send(null)', function(){ it('should set body to ""', function(done){ var app = express(); app.use(function...
}) }) describe('.send(Number)', function(){ it('should send as application/json', function(done){ var app = express(); app.use(function(req, res){ res.send(1000); }); request(app) .get('/') .expect(
function(){ it('should set body to ""', function(done){ var app = express(); app.use(function(req, res){ res.send(undefined); }); request(app) .get('/') .expect(200, '', done);
{ "filepath": "test/res.send.js", "language": "javascript", "file_size": 13688, "cut_index": 921, "middle_length": 229 }
test') describe('res', function () { describe('.sendStatus(statusCode)', function () { it('should send the status code and message as body', function (done) { var app = express(); app.use(function(req, res){ res.sendStatus(201); }); request(app) .get('/') .expect(201...
99', done); }) it('should raise error for invalid status code', function (done) { var app = express() app.use(function (req, res) { res.sendStatus(undefined).end() }) request(app) .get('/') .expect
request(app) .get('/') .expect(599, '5
{ "filepath": "test/res.sendStatus.js", "language": "javascript", "file_size": 951, "cut_index": 582, "middle_length": 52 }
unction () { describe('.status(code)', function () { it('should set the status code when valid', function (done) { var app = express(); app.use(function (req, res) { res.status(200).end(); }); request(app) .get('/') .expect(200, done); }); describe('acce...
et the response status code to 201', function (done) { var app = express() app.use(function (req, res) { res.status(201).end() }) request(app) .get('/') .expect(201, done) }) it('
, function (done) { var app = express() app.use(function (req, res) { res.status(101).end() }) request(app) .get('/') .expect(101, done) }) it('should s
{ "filepath": "test/res.status.js", "language": "javascript", "file_size": 4807, "cut_index": 614, "middle_length": 229 }
= require('..'); var request = require('supertest'); var utils = require('./support/utils'); describe('res.vary()', function(){ describe('with no arguments', function(){ it('should throw error', function (done) { var app = express(); app.use(function (req, res) { res.vary(); res.end...
one); }) }) describe('with an array', function(){ it('should set the values', function (done) { var app = express(); app.use(function (req, res) { res.vary(['Accept', 'Accept-Language', 'Accept-Encoding']); res.end
(done) { var app = express(); app.use(function (req, res) { res.vary([]); res.end(); }); request(app) .get('/') .expect(utils.shouldNotHaveHeader('Vary')) .expect(200, d
{ "filepath": "test/res.vary.js", "language": "javascript", "file_size": 1984, "cut_index": 537, "middle_length": 229 }
unction(){ it('should set the header', function(done){ var app = express(); app.use(function(req, res){ res.location('http://google.com/').end(); }); request(app) .get('/') .expect('Location', 'http://google.com/') .expect(200, done) }) it('should preserv...
n('https://google.com?q=\u2603 §10').end() }) request(app) .get('/') .expect('Location', 'https://google.com?q=%E2%98%83%20%C2%A710') .expect(200, done) }) it('should encode data uri', function (done) { var app
p) .get('/') .expect('Location', 'http://google.com') .expect(200, done) }) it('should encode "url"', function (done) { var app = express() app.use(function (req, res) { res.locatio
{ "filepath": "test/res.location.js", "language": "javascript", "file_size": 8421, "cut_index": 716, "middle_length": 229 }
ror: path must be a string to res.sendFile/, done) }) it('should error for non-absolute path', function (done) { var app = createApp('name.txt') request(app) .get('/') .expect(500, /TypeError: path must be absolute/, done) }) it('should transfer a file', function (done) { ...
var app = createApp(path.resolve(fixtures, 'name.txt')); request(app) .get('/') .expect('ETag', /^(?:W\/)?"[^"]+"$/) .expect(200, 'tobi', done); }); it('should 304 when ETag matches', function (done) { var app
ters in string', function (done) { var app = createApp(path.resolve(fixtures, '% of dogs.txt')); request(app) .get('/') .expect(200, '20%', done); }); it('should include ETag', function (done) {
{ "filepath": "test/res.sendFile.js", "language": "javascript", "file_size": 23888, "cut_index": 1331, "middle_length": 229 }
est = require('supertest'); describe('res', function(){ describe('.type(str)', function(){ it('should set the Content-Type based on a filename', function(done){ var app = express(); app.use(function(req, res){ res.type('foo.js').end('var name = "tj";'); }); request(app) .g...
ontent-Type with type/subtype', function(done){ var app = express(); app.use(function(req, res){ res.type('application/vnd.amazon.ebook') .end('var name = "tj";'); }); request(app) .get('/') .expect('
app.use(function(req, res){ res.type('rawr').end('var name = "tj";'); }); request(app) .get('/') .expect('Content-Type', 'application/octet-stream', done); }) it('should set the C
{ "filepath": "test/res.type.js", "language": "javascript", "file_size": 2812, "cut_index": 563, "middle_length": 229 }
, function(){ it('should support absolute paths', function(done){ var app = createApp(); app.locals.user = { name: 'tobi' }; app.use(function(req, res){ res.render(path.join(__dirname, 'fixtures', 'user.tmpl')) }); request(app) .get('/') .expect('<p>tobi</p>', do...
gine" set and file extension to a non-engine module', function (done) { var app = createApp() app.locals.user = { name: 'tobi' } app.use(function (req, res) { res.render(path.join(__dirname, 'fixtures', 'broken.send')) })
pl'); app.use(function(req, res){ res.render(path.join(__dirname, 'fixtures', 'user')) }); request(app) .get('/') .expect('<p>tobi</p>', done); }) it('should error without "view en
{ "filepath": "test/res.render.js", "language": "javascript", "file_size": 9137, "cut_index": 716, "middle_length": 229 }
est = require('supertest'); describe('res', function(){ describe('.set(field, value)', function(){ it('should set the response header field', function(done){ var app = express(); app.use(function(req, res){ res.set('Content-Type', 'text/x-foo; charset=utf-8').end(); }); request(...
}) }) describe('.set(field, values)', function(){ it('should set multiple response header fields', function(done){ var app = express(); app.use(function(req, res){ res.set('Set-Cookie', ["type=ninja", "language=javascript"]);
app.use(function (req, res) { res.set('X-Number', 123); res.end(typeof res.get('X-Number')); }); request(app) .get('/') .expect('X-Number', '123') .expect(200, 'string', done);
{ "filepath": "test/res.set.js", "language": "javascript", "file_size": 2960, "cut_index": 563, "middle_length": 229 }
return res.headers['set-cookie'][0].split(';')[0]; } describe('auth', function(){ describe('GET /',function(){ it('should redirect to /login', function(done){ request(app) .get('/') .expect('Location', '/login') .expect(302, done) }) }) describe('GET /login',function(){ it...
request(app) .get('/login') .set('Cookie', getCookie(res)) .expect(200, /Authentication failed/, done) }) }) it('should display login error for bad password', function (done) { request(app) .post('/
{ request(app) .post('/login') .type('urlencoded') .send('username=not-tj&password=foobar') .expect('Location', '/login') .expect(302, function(err, res){ if (err) return done(err)
{ "filepath": "test/acceptance/auth.js", "language": "javascript", "file_size": 3064, "cut_index": 614, "middle_length": 229 }
ibe('cookie-sessions', function () { describe('GET /', function () { it('should display no views', function (done) { request(app) .get('/') .expect(200, 'viewed 1 times\n', done) }) it('should set a session cookie', function (done) { request(app) .get('/') .expect('Set...
) request(app) .get('/') .set('Cookie', getCookies(res)) .expect(200, 'viewed 2 times\n', done) }) }) }) }) function getCookies(res) { return res.headers['set-cookie'].map(function (val) { return val.split
nction (err, res) { if (err) return done(err
{ "filepath": "test/acceptance/cookie-sessions.js", "language": "javascript", "file_size": 942, "cut_index": 606, "middle_length": 52 }
equire('../../examples/downloads') , request = require('supertest'); describe('downloads', function(){ describe('GET /', function(){ it('should have a link to amazing.txt', function(done){ request(app) .get('/') .expect(/href="\/files\/amazing.txt"/, done) }) }) describe('GET /files/...
zing.txt') .expect('Content-Disposition', 'attachment; filename="amazing.txt"') .expect(200, done) }) }) describe('GET /files/missing.txt', function(){ it('should respond with 404', function(done){ request(app) .get('/f
', 'attachment; filename="groceries.txt"') .expect(200, done) }) }) describe('GET /files/amazing.txt', function(){ it('should have a download header', function(done){ request(app) .get('/files/ama
{ "filepath": "test/acceptance/downloads.js", "language": "javascript", "file_size": 1265, "cut_index": 524, "middle_length": 229 }
p = require('../../examples/multi-router') var request = require('supertest') describe('multi-router', function(){ describe('GET /',function(){ it('should respond with root handler', function(done){ request(app) .get('/') .expect(200, 'Hello from root route.', done) }) }) describe('GET...
ribe('GET /api/v2/',function(){ it('should respond with APIv2 root handler', function(done){ request(app) .get('/api/v2/') .expect(200, 'Hello from APIv2 root route.', done) }) }) describe('GET /api/v2/users',function(){
) }) describe('GET /api/v1/users',function(){ it('should respond with users from APIv1', function(done){ request(app) .get('/api/v1/users') .expect(200, 'List of APIv1 users.', done) }) }) desc
{ "filepath": "test/acceptance/multi-router.js", "language": "javascript", "file_size": 1173, "cut_index": 518, "middle_length": 229 }
app = require('../../examples/params') var request = require('supertest') describe('params', function(){ describe('GET /', function(){ it('should respond with instructions', function(done){ request(app) .get('/') .expect(/Visit/,done) }) }) describe('GET /user/0', function(){ ...
one){ request(app) .get('/users/0-2') .expect(/users tj, tobi, loki/, done) }) }) describe('GET /users/foo-bar', function(){ it('should fail integer parsing', function(done){ request(app) .get('/users/foo-bar')
il to find user', function(done){ request(app) .get('/user/9') .expect(404, /failed to find user/, done) }) }) describe('GET /users/0-2', function(){ it('should respond with three users', function(d
{ "filepath": "test/acceptance/params.js", "language": "javascript", "file_size": 1064, "cut_index": 515, "middle_length": 229 }
var request = require('supertest') , app = require('../../examples/route-map'); describe('route-map', function(){ describe('GET /users', function(){ it('should respond with users', function(done){ request(app) .get('/users') .expect('user list', done); }) }) describe('DELETE /users',...
request(app) .get('/users/12/pets') .expect('user 12\'s pets', done); }) }) describe('GET /users/:id/pets/:pid', function(){ it('should get a users pet', function(done){ request(app) .del('/users/12/pets/2') .e
it('should get a user', function(done){ request(app) .get('/users/12') .expect('user 12', done); }) }) describe('GET /users/:id/pets', function(){ it('should get a users pets', function(done){
{ "filepath": "test/acceptance/route-map.js", "language": "javascript", "file_size": 1048, "cut_index": 513, "middle_length": 229 }
p = require('../../examples/vhost') var request = require('supertest') describe('vhost', function(){ describe('example.com', function(){ describe('GET /', function(){ it('should say hello', function(done){ request(app) .get('/') .set('Host', 'example.com') .expect(200, /hell...
.set('Host', 'foo.example.com') .expect(302, /Redirecting to http:\/\/example.com:3000\/foo/, done) }) }) }) describe('bar.example.com', function(){ describe('GET /', function(){ it('should redirect to /bar', function
.expect(200, 'requested foo', done) }) }) }) describe('foo.example.com', function(){ describe('GET /', function(){ it('should redirect to /foo', function(done){ request(app) .get('/')
{ "filepath": "test/acceptance/vhost.js", "language": "javascript", "file_size": 1190, "cut_index": 518, "middle_length": 229 }
= require('supertest') , app = require('../../examples/content-negotiation'); describe('content-negotiation', function(){ describe('GET /', function(){ it('should default to text/html', function(done){ request(app) .get('/') .expect(200, '<ul><li>Tobi</li><li>Loki</li><li>Jane</li></ul>', do...
}) describe('GET /users', function(){ it('should default to text/html', function(done){ request(app) .get('/users') .expect(200, '<ul><li>Tobi</li><li>Loki</li><li>Jane</li></ul>', done) }) it('should accept to text/plai
}) it('should accept to application/json', function(done){ request(app) .get('/') .set('Accept', 'application/json') .expect(200, '[{"name":"Tobi"},{"name":"Loki"},{"name":"Jane"}]', done) })
{ "filepath": "test/acceptance/content-negotiation.js", "language": "javascript", "file_size": 1402, "cut_index": 524, "middle_length": 229 }
, request = require('supertest'); describe('error-pages', function(){ describe('GET /', function(){ it('should respond with page list', function(done){ request(app) .get('/') .expect(/Pages Example/, done) }) }) describe('Accept: text/html',function(){ describe('GET /403', function...
(app) .get('/500') .expect(500, done) }) }) }) describe('Accept: application/json',function(){ describe('GET /403', function(){ it('should respond with 403', function(done){ request(app) .get('/403')
uld respond with 404', function(done){ request(app) .get('/404') .expect(404, done) }) }) describe('GET /500', function(){ it('should respond with 500', function(done){ request
{ "filepath": "test/acceptance/error-pages.js", "language": "javascript", "file_size": 2315, "cut_index": 563, "middle_length": 229 }
examples/resource') var request = require('supertest') describe('resource', function(){ describe('GET /', function(){ it('should respond with instructions', function(done){ request(app) .get('/') .expect(/^<h1>Examples:<\/h1>/,done) }) }) describe('GET /users', function(){ it('...
}) describe('GET /users/9', function(){ it('should respond with error', function(done){ request(app) .get('/users/9') .expect('{"error":"Cannot find user"}', done) }) }) describe('GET /users/1..3', function(){ it
on"},{"name":"tobi"}\]/,done) }) }) describe('GET /users/1', function(){ it('should respond with user 1', function(done){ request(app) .get('/users/1') .expect(/^{"name":"ciaran"}/,done) })
{ "filepath": "test/acceptance/resource.js", "language": "javascript", "file_size": 1844, "cut_index": 537, "middle_length": 229 }
/examples/cookies') , request = require('supertest'); var utils = require('../support/utils'); describe('cookies', function(){ describe('GET /', function(){ it('should have a form', function(done){ request(app) .get('/') .expect(/<form/, done); }) it('should respond with no cookies',...
headers['set-cookie'][0]) .expect(200, /Remembered/, done) }) }) }) describe('GET /forget', function(){ it('should clear cookie', function(done){ request(app) .post('/') .type('urlencoded') .send({ remembe
request(app) .post('/') .type('urlencoded') .send({ remember: 1 }) .expect(302, function(err, res){ if (err) return done(err) request(app) .get('/') .set('Cookie', res.
{ "filepath": "test/acceptance/cookies.js", "language": "javascript", "file_size": 1746, "cut_index": 537, "middle_length": 229 }
') var request = require('supertest') describe('route-separation', function () { describe('GET /', function () { it('should respond with index', function (done) { request(app) .get('/') .expect(200, /Route Separation Example/, done) }) }) describe('GET /users', function () { it('sh...
('/user/10') .expect(404, done) }) }) describe('GET /user/:id/view', function () { it('should get a user', function (done) { request(app) .get('/user/0/view') .expect(200, /Viewing user TJ/, done) }) it('should
() { it('should get a user', function (done) { request(app) .get('/user/0') .expect(200, /Viewing user TJ/, done) }) it('should 404 on missing user', function (done) { request(app) .get
{ "filepath": "test/acceptance/route-separation.js", "language": "javascript", "file_size": 2541, "cut_index": 563, "middle_length": 229 }
(){ describe('GET /', function(){ it('should redirect to /users', function(done){ request(app) .get('/') .expect('Location', '/users') .expect(302, done) }) }) describe('GET /pet/0', function(){ it('should get pet', function(done){ request(app) .get('/pet/0') ...
rm-urlencoded') .send({ pet: { name: 'Boots' } }) .expect(302, function (err, res) { if (err) return done(err); request(app) .get('/pet/3/edit') .expect(200, /Boots/, done) }) }) }) describe('GET /
(/<form/) .expect(200, /Tobi/, done) }) }) describe('PUT /pet/2', function(){ it('should update the pet', function(done){ request(app) .put('/pet/3') .set('Content-Type', 'application/x-www-fo
{ "filepath": "test/acceptance/mvc.js", "language": "javascript", "file_size": 3292, "cut_index": 614, "middle_length": 229 }
ssert = require('node:assert'); const { Buffer } = require('node:buffer'); /** * Module exports. * @public */ exports.shouldHaveBody = shouldHaveBody exports.shouldHaveHeader = shouldHaveHeader exports.shouldNotHaveBody = shouldNotHaveBody exports.shouldNotHaveHeader = shouldNotHaveHeader; exports.shouldSkipQuery ...
test response does have a header. * * @param {string} header Header name to check * @returns {function} */ function shouldHaveHeader (header) { return function (res) { assert.ok((header.toLowerCase() in res.headers), 'should have header ' + head
var body = !Buffer.isBuffer(res.body) ? Buffer.from(res.text) : res.body assert.ok(body, 'response has body') assert.strictEqual(body.toString('hex'), buf.toString('hex')) } } /** * Assert that a super
{ "filepath": "test/support/utils.js", "language": "javascript", "file_size": 2089, "cut_index": 563, "middle_length": 229 }
"""Check release-notes.md and add today's date to the latest release header if missing.""" import re import sys from datetime import date RELEASE_NOTES_FILE = "docs/en/docs/release-notes.md" RELEASE_HEADER_PATTERN = re.compile(r"^## (\d+\.\d+\.\d+)\s*(\(.*\))?\s*$") def main() -> None: with open(RELEASE_NOTES_F...
es[i] = f"## {version} ({today})\n" print(f"Added date: {version} ({today})") with open(RELEASE_NOTES_FILE, "w") as f: f.writelines(lines) sys.exit(0) print("No release header found") sys.exit(1) if __name__
match.group(1) date_part = match.group(2) if date_part: print(f"Latest release {version} already has a date: {date_part}") sys.exit(0) today = date.today().isoformat() lin
{ "filepath": "scripts/add_latest_release_date.py", "language": "python", "file_size": 1023, "cut_index": 512, "middle_length": 229 }
ort BaseModel, SecretStr from pydantic_settings import BaseSettings class Settings(BaseSettings): github_repository: str github_token: SecretStr deploy_url: str | None = None commit_sha: str run_id: int state: Literal["pending", "success", "error"] = "pending" class LinkData(BaseModel): ...
.sha == settings.commit_sha), None ) if not use_pr: logging.error(f"No PR found for hash: {settings.commit_sha}") return commits = list(use_pr.get_commits()) current_commit = [c for c in commits if c.sha == settings.commit_s
nfig: {settings.model_dump_json()}") g = Github(auth=Auth.Token(settings.github_token.get_secret_value())) repo = g.get_repo(settings.github_repository) use_pr = next( (pr for pr in repo.get_pulls() if pr.head
{ "filepath": "scripts/deploy_docs_status.py", "language": "python", "file_size": 4552, "cut_index": 614, "middle_length": 229 }
ment.md", "contributing.md", "translations.md", ) docs_path = Path("docs") en_docs_path = Path("docs/en") en_config_path: Path = en_docs_path / mkdocs_name site_path = Path("site").absolute() zensical_src_path = Path("site_zensical_src").absolute() header_pattern = re.compile(r"^(#{1,6}) (.+?)(?:\s*\{\s*(#.*)...
md_link_pattern.sub(r"\1", text) class VisibleTextExtractor(HTMLParser): """Extract visible text from a string with HTML tags.""" def __init__(self): super().__init__() self.text_parts = [] def handle_data(self, data):
# Pattern to match markdown links: [text](url) → text md_link_pattern = re.compile(r"\[([^\]]+)\]\([^)]+\)") def strip_markdown_links(text: str) -> str: """Replace markdown links with just their visible text.""" return
{ "filepath": "scripts/docs.py", "language": "python", "file_size": 30330, "cut_index": 1331, "middle_length": 229 }
BaseModel, SecretStr from pydantic_settings import BaseSettings github_graphql_url = "https://api.github.com/graphql" sponsors_query = """ query Q($after: String) { user(login: "tiangolo") { sponsorshipsAsMaintainer(first: 100, after: $after) { edges { cursor node { sponsorEnti...
tr class Tier(BaseModel): name: str monthlyPriceInDollars: float class SponsorshipAsMaintainerNode(BaseModel): sponsorEntity: SponsorEntity tier: Tier class SponsorshipAsMaintainerEdge(BaseModel): cursor: str node: Sponsorship
url } } tier { name monthlyPriceInDollars } } } } } } """ class SponsorEntity(BaseModel): login: str avatarUrl: str url: s
{ "filepath": "scripts/sponsors.py", "language": "python", "file_size": 6247, "cut_index": 716, "middle_length": 229 }
ocess import time import httpx from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually con...
# Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/query-param-models/image01.png") # --------------------- context.close() browser.close() process = subprocess.Popen( ["fastapi", "run", "docs_src/query_p
page.goto("http://localhost:8000/docs") page.get_by_role("button", name="GET /items/ Read Items").click() page.get_by_role("button", name="Try it out").click() page.get_by_role("heading", name="Servers").click()
{ "filepath": "scripts/playwright/query_param_models/image01.py", "language": "python", "file_size": 1322, "cut_index": 524, "middle_length": 229 }
aywright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = cont...
path="docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png" ) # --------------------- context.close() browser.close() process = subprocess.Popen( ["uvicorn", "docs_src.separate_openapi_schemas.tutorial002:app"] ) try: w
lly add the screenshot page.screenshot(
{ "filepath": "scripts/playwright/separate_openapi_schemas/image05.py", "language": "python", "file_size": 984, "cut_index": 582, "middle_length": 52 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_header_permalinks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_level_misma...
).read_text("utf-8") assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Header levels do not match between document and original docum
doc.md"], ) assert result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path( f"{data_path}/translated_doc_level_mismatch_1.md"
{ "filepath": "scripts/tests/test_translation_fixer/test_header_permalinks/test_header_level_mismatch.py", "language": "python", "file_size": 1999, "cut_index": 537, "middle_length": 229 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_markdown_links/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")...
) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of markdown links does not match the number " "in the original
rt result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8"
{ "filepath": "scripts/tests/test_translation_fixer/test_markdown_links/test_mkd_links_number_mismatch.py", "language": "python", "file_size": 1911, "cut_index": 537, "middle_length": 229 }
wordRequestForm, SecurityScopes, ) from jwt.exceptions import InvalidTokenError from pwdlib import PasswordHash from pydantic import BaseModel, ValidationError # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" ALGORITHM = "HS256"...
"email": "alicechains@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } class Token(BaseModel): access_token: str
assword": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains",
{ "filepath": "docs_src/security/tutorial005_py310.py", "language": "python", "file_size": 5418, "cut_index": 716, "middle_length": 229 }
import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Item = Body( openapi_examples={ ...
e with converted data", "description": "FastAPI can convert price `strings` to actual `numbers` automatically", "value": { "name": "Bar", "price": "35.4", },
: "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, }, "converted": { "summary": "An exampl
{ "filepath": "docs_src/schema_extra_example/tutorial005_py310.py", "language": "python", "file_size": 1348, "cut_index": 524, "middle_length": 229 }
m collections.abc import AsyncIterable, Iterable from fastapi import FastAPI from fastapi.sse import EventSourceResponse from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None items = [ Item(name="Plumbus", description="A multi-purpose household device....
for item in items: yield item @app.get("/items/stream-no-annotation", response_class=EventSourceResponse) async def sse_items_no_annotation(): for item in items: yield item @app.get("/items/stream-no-async-no-annotation", respon
ss=EventSourceResponse) async def sse_items() -> AsyncIterable[Item]: for item in items: yield item @app.get("/items/stream-no-async", response_class=EventSourceResponse) def sse_items_no_async() -> Iterable[Item]:
{ "filepath": "docs_src/server_sent_events/tutorial001_py310.py", "language": "python", "file_size": 1112, "cut_index": 515, "middle_length": 229 }
pi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float = 10.5 items = { "foo": {"name": "Foo", "price": 50.2}, "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2...
response_model_include={"name", "description"}, ) async def read_item_name(item_id: str): return items[item_id] @app.get("/items/{item_id}/public", response_model=Item, response_model_exclude={"tax"}) async def read_item_public_data(item_id: str):
del=Item,
{ "filepath": "docs_src/response_model/tutorial005_py310.py", "language": "python", "file_size": 816, "cut_index": 522, "middle_length": 14 }
ithub from pydantic import BaseModel, SecretStr from pydantic_settings import BaseSettings github_graphql_url = "https://api.github.com/graphql" prs_query = """ query Q($after: String) { repository(name: "fastapi", owner: "fastapi") { pullRequests(first: 100, after: $after) { edges { cursor ...
arUrl url } state } } } } } } } """ class Author(BaseModel): login: str avatarUrl: str url: str class LabelNode(BaseModel): name: str class Labels(B
url } title createdAt lastEditedAt updatedAt state reviews(first:100) { nodes { author { login avat
{ "filepath": "scripts/contributors.py", "language": "python", "file_size": 8807, "cut_index": 716, "middle_length": 229 }
= re.compile(r"<a\b([^>]*)>(.*?)</a>") HTML_LINK_OPEN_TAG_RE = re.compile(r"<a\b([^>]*)>") HTML_ATTR_RE = re.compile(r'(\w+)\s*=\s*([\'"])(.*?)\2') CODE_BLOCK_LANG_RE = re.compile(r"^`{3,4}([\w-]*)", re.MULTILINE) SLASHES_COMMENT_RE = re.compile( r"^(?P<code>.*?)(?P<comment>(?:(?<= )// .*)|(?:^// .*))?$" ) HASH...
nkAttribute(TypedDict): name: str quote: str value: str class HtmlLinkInfo(TypedDict): line_no: int full_tag: str attributes: list[HTMLLinkAttribute] text: str class MultilineCodeBlockInfo(TypedDict): lang: str start
line_no: int hashes: str title: str permalink: str class MarkdownLinkInfo(TypedDict): line_no: int url: str text: str title: str | None attributes: str | None full_match: str class HTMLLi
{ "filepath": "scripts/doc_parsing_utils.py", "language": "python", "file_size": 24109, "cut_index": 1331, "middle_length": 229 }
hub import Github from github.PullRequestReview import PullRequestReview from pydantic import BaseModel, SecretStr from pydantic_settings import BaseSettings class LabelSettings(BaseModel): await_label: str | None = None number: int default_config = {"approved-2": LabelSettings(await_label="awaiting-review"...
secret_value()) repo = g.get_repo(settings.github_repository) for pr in repo.get_pulls(state="open"): logging.info(f"Checking PR: #{pr.number}") pr_labels = list(pr.get_labels()) pr_label_by_name = {label.name: label for label in pr_labels}
settings = Settings() if settings.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logging.debug(f"Using config: {settings.model_dump_json()}") g = Github(settings.token.get_
{ "filepath": "scripts/label_approved.py", "language": "python", "file_size": 2245, "cut_index": 563, "middle_length": 229 }
ttings github_graphql_url = "https://api.github.com/graphql" questions_category_id = "DIC_kwDOCZduT84B6E2a" POINTS_PER_MINUTE_LIMIT = 84 # 5000 points per hour MINIMIZED_COMMENTS_REASONS_TO_EXCLUDE = {"abuse", "off-topic", "duplicate", "spam"} class RateLimiter: def __init__(self) -> None: self.last_...
ime = 0.0 if self.remaining_points <= self.last_query_cost: primary_limit_wait_time = (self.reset_at - now).total_seconds() + 2 logging.warning( f"Approaching GitHub API rate limit, remaining points: {self.re
e.fromtimestamp(0, timezone.utc) self.speed_multiplier: float = 1.0 def __enter__(self) -> "RateLimiter": now = datetime.now(tz=timezone.utc) # Handle primary rate limits primary_limit_wait_t
{ "filepath": "scripts/people.py", "language": "python", "file_size": 15382, "cut_index": 921, "middle_length": 229 }
ory_id = "DIC_kwDOCZduT84CT5P9" all_discussions_query = """ query Q($category_id: ID) { repository(name: "fastapi", owner: "fastapi") { discussions(categoryId: $category_id, first: 100) { nodes { title id number labels(first: 10) { edges { node { ...
} } } } } } """ add_comment_mutation = """ mutation Q($discussion_id: ID!, $body: String!) { addDiscussionComment(input: {discussionId: $discussion_id, body: $body}) { comment { id url body } } } """
ame: "fastapi", owner: "fastapi") { discussion(number: $discussion_number) { comments(first: 100, after: $after) { edges { cursor node { id url body
{ "filepath": "scripts/notify_translations.py", "language": "python", "file_size": 12930, "cut_index": 921, "middle_length": 229 }
m pathlib import Path import yaml from github import Github from pydantic import BaseModel, SecretStr from pydantic_settings import BaseSettings class Settings(BaseSettings): github_repository: str github_token: SecretStr class Repo(BaseModel): name: str html_url: str stars: int owner_login...
[] for repo in repos_list[:100]: if repo.full_name == settings.github_repository: continue final_repos.append( Repo( name=repo.name, html_url=repo.html_url, stars=r
= Github(settings.github_token.get_secret_value(), per_page=100) r = g.get_repo(settings.github_repository) repos = g.search_repositories(query="topic:fastapi") repos_list = list(repos) final_repos: list[Repo] =
{ "filepath": "scripts/topic_repos.py", "language": "python", "file_size": 2803, "cut_index": 563, "middle_length": 229 }
import typer from scripts.doc_parsing_utils import check_translation non_translated_sections = ( f"reference{os.sep}", "release-notes.md", "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", "management.md", "contributing.md", "translations.md", ) cl...
irst_parent = lang_path_root yield from first_parent.glob("*.md") for dir_path in first_dirs: yield from dir_path.rglob("*.md") first_dirs_str = tuple(str(d) for d in first_dirs) for path in lang_path_root.rglob("*.md"): if
of priority. """ first_dirs = [ lang_path_root / "learn", lang_path_root / "tutorial", lang_path_root / "advanced", lang_path_root / "about", lang_path_root / "how-to", ] f
{ "filepath": "scripts/translation_fixer.py", "language": "python", "file_size": 3311, "cut_index": 614, "middle_length": 229 }
thsep}", "release-notes.md", "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", "management.md", "contributing.md", "translations.md", ) general_prompt_path = Path(__file__).absolute().parent / "general-llm-prompt.md" general_prompt = general_prompt_path.r...
/{lang}/docs") out_path = Path(str(path).replace(str(en_docs_path), str(lang_docs_path))) return out_path def generate_en_path(*, lang: str, path: Path) -> Path: en_docs_path = Path("docs/en/docs") assert not str(path).startswith(str(en_d
erate_lang_path(*, lang: str, path: Path) -> Path: en_docs_path = Path("docs/en/docs") assert str(path).startswith(str(en_docs_path)), ( f"Path must be inside {en_docs_path}" ) lang_docs_path = Path(f"docs
{ "filepath": "scripts/translate.py", "language": "python", "file_size": 17252, "cut_index": 921, "middle_length": 229 }
subprocess import time import httpx from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually ...
--------------------- context.close() browser.close() process = subprocess.Popen( ["fastapi", "run", "docs_src/cookie_param_models/tutorial001.py"] ) try: for _ in range(3): try: response = httpx.get("http://localhost:
ge() page.goto("http://localhost:8000/docs") page.get_by_role("link", name="/items/").click() # Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/cookie-param-models/image01.png") #
{ "filepath": "scripts/playwright/cookie_param_models/image01.py", "language": "python", "file_size": 1193, "cut_index": 518, "middle_length": 229 }
subprocess import time import httpx from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually ...
context.close() browser.close() process = subprocess.Popen( ["fastapi", "run", "docs_src/request_form_models/tutorial001.py"] ) try: for _ in range(3): try: response = httpx.get("http://localhost:8000/docs") ex
ogin/ Login").click() page.get_by_role("button", name="Try it out").click() # Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png") # ---------------------
{ "filepath": "scripts/playwright/request_form_models/image01.py", "language": "python", "file_size": 1171, "cut_index": 518, "middle_length": 229 }
mport subprocess from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually context = browser...
.png" ) # --------------------- context.close() browser.close() process = subprocess.Popen( ["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"] ) try: with sync_playwright() as playwright: run(playwright) fin
t_by_role("button", name="Try it out").click() page.get_by_role("button", name="Execute").click() # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image02
{ "filepath": "scripts/playwright/separate_openapi_schemas/image02.py", "language": "python", "file_size": 1028, "cut_index": 513, "middle_length": 229 }
mport subprocess from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually context = browser...
api-schemas/image03.png" ) # --------------------- context.close() browser.close() process = subprocess.Popen( ["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"] ) try: with sync_playwright() as playwright:
t_by_role("tab", name="Schema").click() page.get_by_label("Schema").get_by_role("button", name="Expand all").click() # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-open
{ "filepath": "scripts/playwright/separate_openapi_schemas/image03.py", "language": "python", "file_size": 1047, "cut_index": 513, "middle_length": 229 }
mport subprocess from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually context = browser...
s/image04.png" ) # --------------------- context.close() browser.close() process = subprocess.Popen( ["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"] ) try: with sync_playwright() as playwright: run(playwri
ge.get_by_role("button", name="Item-Output").click() page.set_viewport_size({"width": 960, "height": 820}) # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schema
{ "filepath": "scripts/playwright/separate_openapi_schemas/image04.py", "language": "python", "file_size": 1036, "cut_index": 513, "middle_length": 229 }
aywright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = cont...
/en/docs/img/tutorial/separate-openapi-schemas/image01.png" ) # --------------------- context.close() browser.close() process = subprocess.Popen( ["uvicorn", "docs_src.separate_openapi_schemas.tutorial001:app"] ) try: with sync_p
e screenshot page.screenshot( path="docs
{ "filepath": "scripts/playwright/separate_openapi_schemas/image01.py", "language": "python", "file_size": 974, "cut_index": 582, "middle_length": 52 }
ort subprocess import time import httpx from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manuall...
process.Popen( ["fastapi", "run", "docs_src/json_base64_bytes/tutorial001_py310.py"] ) try: for _ in range(3): try: response = httpx.get("http://localhost:8000/docs") except httpx.ConnectError: time.sleep(1)
/data Post Data").click() # Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/json-base64-bytes/image01.png") # --------------------- context.close() browser.close() process = sub
{ "filepath": "scripts/playwright/json_base64_bytes/image01.py", "language": "python", "file_size": 1117, "cut_index": 515, "middle_length": 229 }
ort subprocess import time import httpx from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manuall...
api", "run", "docs_src/sql_databases/tutorial002.py"], ) try: for _ in range(3): try: response = httpx.get("http://localhost:8000/docs") except httpx.ConnectError: time.sleep(1) break with sync_pl
ick() # Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image02.png") # --------------------- context.close() browser.close() process = subprocess.Popen( ["fast
{ "filepath": "scripts/playwright/sql_databases/image02.py", "language": "python", "file_size": 1083, "cut_index": 515, "middle_length": 229 }
mport sys from collections.abc import Generator from contextlib import contextmanager from pathlib import Path import pytest from typer.testing import CliRunner skip_on_windows = pytest.mark.skipif( sys.platform == "win32", reason="Skipping on Windows" ) THIS_DIR = Path(__file__).parent.resolve() def pytest_c...
try: yield finally: os.chdir(initial_dir) @pytest.fixture(name="runner") def get_runner(tmp_path: Path): with changing_dir(tmp_path): yield CliRunner() @pytest.fixture(name="root_dir") def prepare_paths(runner): d
if item_path.is_relative_to(THIS_DIR): item.add_marker(skip_on_windows) @contextmanager def changing_dir(directory: str | Path) -> Generator[None, None, None]: initial_dir = os.getcwd() os.chdir(directory)
{ "filepath": "scripts/tests/test_translation_fixer/conftest.py", "language": "python", "file_size": 1637, "cut_index": 537, "middle_length": 229 }
subprocess import time import httpx from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manually ...
--- context.close() browser.close() process = subprocess.Popen( ["fastapi", "run", "docs_src/header_param_models/tutorial001.py"] ) try: for _ in range(3): try: response = httpx.get("http://localhost:8000/docs")
ems/ Read Items").click() page.get_by_role("button", name="Try it out").click() # Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/header-param-models/image01.png") # ------------------
{ "filepath": "scripts/playwright/header_param_models/image01.py", "language": "python", "file_size": 1175, "cut_index": 518, "middle_length": 229 }
ort subprocess import time import httpx from playwright.sync_api import Playwright, sync_playwright # Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) # Update the viewport manuall...
api", "run", "docs_src/sql_databases/tutorial001.py"], ) try: for _ in range(3): try: response = httpx.get("http://localhost:8000/docs") except httpx.ConnectError: time.sleep(1) break with sync_pl
ick() # Manually add the screenshot page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image01.png") # --------------------- context.close() browser.close() process = subprocess.Popen( ["fast
{ "filepath": "scripts/playwright/sql_databases/image01.py", "language": "python", "file_size": 1083, "cut_index": 515, "middle_length": 229 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_header_permalinks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.m...
sert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of headers with permalinks does not match the number " "in the original doc
ssert result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8" ) as
{ "filepath": "scripts/tests/test_translation_fixer/test_header_permalinks/test_header_number_mismatch.py", "language": "python", "file_size": 1900, "cut_index": 537, "middle_length": 229 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_blocks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_lines_number_gt.m...
"utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Code block (lines 14-18) has different number of lines than the origi
ssert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_lines_number_gt.md").read_text(
{ "filepath": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_lines_number_mismatch.py", "language": "python", "file_size": 1916, "cut_index": 537, "middle_length": 229 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_blocks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")], ...
) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of code blocks does not match the number " "in the original docume
result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8"
{ "filepath": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_number_mismatch.py", "language": "python", "file_size": 1902, "cut_index": 537, "middle_length": 229 }
test from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_complex_doc/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc.md")], indirect=True, )...
docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = (data_path / "translated_doc_expected.md").read_text("utf-8") assert fixed_content == expected_content assert "Fixing multiline code blocks in" in result.output asse
0, result.output fixed_content = (root_dir / "
{ "filepath": "scripts/tests/test_translation_fixer/test_complex_doc/test_compex_doc.py", "language": "python", "file_size": 902, "cut_index": 547, "middle_length": 52 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_blocks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_wrong_lang_code.m...
_text( "utf-8" ) assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Code block (lines 16-19) has different language than t
"], ) assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_wrong_lang_code.md").read
{ "filepath": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_wrong_lang_code.py", "language": "python", "file_size": 1950, "cut_index": 537, "middle_length": 229 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_blocks/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_mermaid_translate...
d" ).read_text("utf-8") assert fixed_content == expected_content # Translated doc remains unchanged assert ( "Skipping mermaid code block replacement (lines 41-44). This should be checked manually." ) in result.output @pytest.ma
) assert result.exit_code == 0, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path( f"{data_path}/translated_doc_mermaid_translated.m
{ "filepath": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_mermaid.py", "language": "python", "file_size": 1807, "cut_index": 537, "middle_length": 229 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path( "scripts/tests/test_translation_fixer/test_code_includes/data" ).absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")]...
fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of code include placeholders does not match the number of code includes " "in t
t result.exit_code == 1 fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8" ) assert
{ "filepath": "scripts/tests/test_translation_fixer/test_code_includes/test_number_mismatch.py", "language": "python", "file_size": 1934, "cut_index": 537, "middle_length": 229 }
import pytest from typer.testing import CliRunner from scripts.translation_fixer import cli data_path = Path("scripts/tests/test_translation_fixer/test_html_links/data").absolute() @pytest.mark.parametrize( "copy_test_files", [(f"{data_path}/en_doc.md", f"{data_path}/translated_doc_number_gt.md")], ind...
assert fixed_content == expected_content # Translated doc remains unchanged assert "Error processing docs/lang/docs/doc.md" in result.output assert ( "Number of HTML links does not match the number " "in the original document (7 vs
exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content = Path(f"{data_path}/translated_doc_number_gt.md").read_text( "utf-8" )
{ "filepath": "scripts/tests/test_translation_fixer/test_html_links/test_html_links_number_mismatch.py", "language": "python", "file_size": 1893, "cut_index": 537, "middle_length": 229 }
epends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from pydantic import BaseModel fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "fakeh...
odel): username: str email: str | None = None full_name: str | None = None disabled: bool | None = None class UserInDB(User): hashed_password: str def get_user(db, username: str): if username in db: user_dict = db[userna
rd": "fakehashedsecret2", "disabled": True, }, } app = FastAPI() def fake_hash_password(password: str): return "fakehashed" + password oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") class User(BaseM
{ "filepath": "docs_src/security/tutorial003_an_py310.py", "language": "python", "file_size": 2517, "cut_index": 563, "middle_length": 229 }
, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from pydantic import BaseModel fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "fakehashedsecret", "disable...
mail: str | None = None full_name: str | None = None disabled: bool | None = None class UserInDB(User): hashed_password: str def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**
"disabled": True, }, } app = FastAPI() def fake_hash_password(password: str): return "fakehashed" + password oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") class User(BaseModel): username: str e
{ "filepath": "docs_src/security/tutorial003_py310.py", "language": "python", "file_size": 2433, "cut_index": 563, "middle_length": 229 }
asswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) from jwt.exceptions import InvalidTokenError from pwdlib import PasswordHash from pydantic import BaseModel, ValidationError # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b...
ll_name": "Alice Chains", "email": "alicechains@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } class Token(BaseModel
ample.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "fu
{ "filepath": "docs_src/security/tutorial005_an_py310.py", "language": "python", "file_size": 5509, "cut_index": 716, "middle_length": 229 }
tapi import FastAPI from fastapi.responses import JSONResponse from pydantic import BaseModel class Item(BaseModel): id: str value: str class Message(BaseModel): message: str app = FastAPI() @app.get( "/items/{item_id}", response_model=Item, responses={ 404: {"model": Message, "d...
} }, }, }, ) async def read_item(item_id: str): if item_id == "foo": return {"id": "foo", "value": "there goes my hero"} else: return JSONResponse(status_code=404, content={"message": "Item not
ample": {"id": "bar", "value": "The bar tenders"}
{ "filepath": "docs_src/additional_responses/tutorial003_py310.py", "language": "python", "file_size": 837, "cut_index": 520, "middle_length": 52 }
pi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jwt.exceptions import InvalidTokenError from pwdlib import PasswordHash from pydantic import BaseModel # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "09d25e094faa6c...
n(BaseModel): access_token: str token_type: str class TokenData(BaseModel): username: str | None = None class User(BaseModel): username: str email: str | None = None full_name: str | None = None disabled: bool | None = None
: "John Doe", "email": "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } class Toke
{ "filepath": "docs_src/security/tutorial004_an_py310.py", "language": "python", "file_size": 4300, "cut_index": 614, "middle_length": 229 }
TTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jwt.exceptions import InvalidTokenError from pwdlib import PasswordHash from pydantic import BaseModel # to get a string like this run: # openssl rand -hex 32 SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6...
n: str token_type: str class TokenData(BaseModel): username: str | None = None class User(BaseModel): username: str email: str | None = None full_name: str | None = None disabled: bool | None = None class UserInDB(User): h
: "johndoe@example.com", "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } class Token(BaseModel): access_toke
{ "filepath": "docs_src/security/tutorial004_py310.py", "language": "python", "file_size": 4200, "cut_index": 614, "middle_length": 229 }
ort secrets from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials app = FastAPI() security = HTTPBasic() def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): current_username_bytes = credentials.username.encode("utf8...
ect_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username @app.get("
dentials.password.encode("utf8") correct_password_bytes = b"swordfish" is_correct_password = secrets.compare_digest( current_password_bytes, correct_password_bytes ) if not (is_correct_username and is_corr
{ "filepath": "docs_src/security/tutorial007_py310.py", "language": "python", "file_size": 1116, "cut_index": 515, "middle_length": 229 }
xception_handler, request_validation_exception_handler, ) from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI() @app.exception_handler(StarletteHTTPException) async def custom_http_exception_handler(request, exc): print(...
xc}") return await request_validation_exception_handler(request, exc) @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 3: raise HTTPException(status_code=418, detail="Nope! I don't like 3.") return {"item_
: print(f"OMG! The client sent invalid data!: {e
{ "filepath": "docs_src/handling_errors/tutorial006_py310.py", "language": "python", "file_size": 928, "cut_index": 606, "middle_length": 52 }
ted from fastapi import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Annotated[ Item,...
}, }, "converted": { "summary": "An example with converted data", "description": "FastAPI can convert price `strings` to actual `numbers` automatically", "value":
ly.", "value": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2,
{ "filepath": "docs_src/schema_extra_example/tutorial005_an_py310.py", "language": "python", "file_size": 1523, "cut_index": 537, "middle_length": 229 }
secrets from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials app = FastAPI() security = HTTPBasic() def get_current_username( credentials: Annotated[HTTPBasicCredentials, Depends(security)], ): current_usernam...
if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, )
ytes ) current_password_bytes = credentials.password.encode("utf8") correct_password_bytes = b"swordfish" is_correct_password = secrets.compare_digest( current_password_bytes, correct_password_bytes )
{ "filepath": "docs_src/security/tutorial007_an_py310.py", "language": "python", "file_size": 1172, "cut_index": 518, "middle_length": 229 }
rom fastapi import Body, FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Item = Body( examples=...
e": "Bar", "price": "35.4", }, { "name": "Baz", "price": "thirty five point four", }, ], ), ): results = {"item_id": item_id, "item": item} return resul
"nam
{ "filepath": "docs_src/schema_extra_example/tutorial004_py310.py", "language": "python", "file_size": 786, "cut_index": 513, "middle_length": 14 }
or from fastapi.responses import PlainTextResponse from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI() @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request, exc): return PlainTextResponse(str(exc.detail), status_code=exc.status_code) @app....
r['msg']}" return PlainTextResponse(message, status_code=400) @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 3: raise HTTPException(status_code=418, detail="Nope! I don't like 3.") return {"item_id": ite
message += f"\nField: {error['loc']}, Error: {erro
{ "filepath": "docs_src/handling_errors/tutorial004_py310.py", "language": "python", "file_size": 920, "cut_index": 606, "middle_length": 52 }
t yaml from fastapi import FastAPI, HTTPException, Request from pydantic import BaseModel, ValidationError app = FastAPI() class Item(BaseModel): name: str tags: list[str] @app.post( "/items/", openapi_extra={ "requestBody": { "content": {"application/x-yaml": {"schema": Item.mo...
t yaml.YAMLError: raise HTTPException(status_code=422, detail="Invalid YAML") try: item = Item.model_validate(data) except ValidationError as e: raise HTTPException(status_code=422, detail=e.errors(include_url=False)) re
ody) excep
{ "filepath": "docs_src/path_operation_advanced_configuration/tutorial007_py310.py", "language": "python", "file_size": 797, "cut_index": 517, "middle_length": 14 }
import gzip from collections.abc import Callable from typing import Annotated from fastapi import Body, FastAPI, Request, Response from fastapi.routing import APIRoute class GzipRequest(Request): async def body(self) -> bytes: if not hasattr(self, "_body"): body = await super().body() ...
st.receive) return await original_route_handler(request) return custom_route_handler app = FastAPI() app.router.route_class = GzipRoute @app.post("/sum") async def sum_numbers(numbers: Annotated[list[int], Body()]): return {"su
def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() async def custom_route_handler(request: Request) -> Response: request = GzipRequest(request.scope, reque
{ "filepath": "docs_src/custom_request_and_route/tutorial001_an_py310.py", "language": "python", "file_size": 1015, "cut_index": 512, "middle_length": 229 }
m fastapi import Body, FastAPI, HTTPException, Request, Response from fastapi.exceptions import RequestValidationError from fastapi.routing import APIRoute class ValidationErrorLoggingRoute(APIRoute): def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() as...
detail = {"errors": exc.errors(), "body": body.decode()} raise HTTPException(status_code=422, detail=detail) return custom_route_handler app = FastAPI() app.router.route_class = ValidationErrorLoggingRoute @app.post("/") as
body = await request.body()
{ "filepath": "docs_src/custom_request_and_route/tutorial002_an_py310.py", "language": "python", "file_size": 974, "cut_index": 582, "middle_length": 52 }
mport time from collections.abc import Callable from fastapi import APIRouter, FastAPI, Request, Response from fastapi.routing import APIRoute class TimedRoute(APIRoute): def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() async def custom_route_handler(...
urn response return custom_route_handler app = FastAPI() router = APIRouter(route_class=TimedRoute) @app.get("/") async def not_timed(): return {"message": "Not timed"} @router.get("/timed") async def timed(): return {"message": "It'
esponse.headers["X-Response-Time"] = str(duration) print(f"route duration: {duration}") print(f"route response: {response}") print(f"route response headers: {response.headers}") ret
{ "filepath": "docs_src/custom_request_and_route/tutorial003_py310.py", "language": "python", "file_size": 1051, "cut_index": 513, "middle_length": 229 }
import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None items = [ Item(name="Plumbus", description="A multi-purpose household device."), Item(name="Portal Gun", description="A portal opening device."), Item(name="Meeseeks Box", description="A box that summons ...
yield item @app.get("/items/stream-no-annotation") async def stream_items_no_annotation(): for item in items: yield item @app.get("/items/stream-no-async-no-annotation") def stream_items_no_async_no_annotation(): for item in item
_async() -> Iterable[Item]: for item in items:
{ "filepath": "docs_src/stream_json_lines/tutorial001_py310.py", "language": "python", "file_size": 936, "cut_index": 606, "middle_length": 52 }
t, Response from fastapi.exceptions import RequestValidationError from fastapi.routing import APIRoute class ValidationErrorLoggingRoute(APIRoute): def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() async def custom_route_handler(request: Request) -> Res...
code()} raise HTTPException(status_code=422, detail=detail) return custom_route_handler app = FastAPI() app.router.route_class = ValidationErrorLoggingRoute @app.post("/") async def sum_numbers(numbers: list[int] = Body()):
detail = {"errors": exc.errors(), "body": body.de
{ "filepath": "docs_src/custom_request_and_route/tutorial002_py310.py", "language": "python", "file_size": 935, "cut_index": 606, "middle_length": 52 }
rom fastapi import FastAPI, Request app = FastAPI() def magic_data_reader(raw_body: bytes): return { "size": len(raw_body), "content": { "name": "Maaaagic", "price": 42, "description": "Just kiddin', no magic here. ✨", }, } @app.post( "/items/...
"description": {"type": "string"}, }, } } }, "required": True, }, }, ) async def create_item(request: Request): raw_body = await request.body() data = m
ce"], "type": "object", "properties": { "name": {"type": "string"}, "price": {"type": "number"},
{ "filepath": "docs_src/path_operation_advanced_configuration/tutorial006_py310.py", "language": "python", "file_size": 1043, "cut_index": 513, "middle_length": 229 }
rom fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files(files: list[bytes] = File()): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files(files: list[UploadFile]...
es" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ return HTMLResponse(content=conten
nput name="fil
{ "filepath": "docs_src/request_files/tutorial002_py310.py", "language": "python", "file_size": 786, "cut_index": 513, "middle_length": 14 }
UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files( files: list[bytes] = File(description="Multiple files as bytes"), ): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files( files: l...
ethod="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ retu
orm action="/files/" enctype="multipart/form-data" m
{ "filepath": "docs_src/request_files/tutorial003_py310.py", "language": "python", "file_size": 888, "cut_index": 547, "middle_length": 52 }
Body, FastAPI, Request, Response from fastapi.routing import APIRoute class GzipRequest(Request): async def body(self) -> bytes: if not hasattr(self, "_body"): body = await super().body() if "gzip" in self.headers.getlist("Content-Encoding"): body = gzip.decompress(...
: Request) -> Response: request = GzipRequest(request.scope, request.receive) return await original_route_handler(request) return custom_route_handler app = FastAPI() app.router.route_class = GzipRoute @app.post("/sum")
er() async def custom_route_handler(request
{ "filepath": "docs_src/custom_request_and_route/tutorial001_py310.py", "language": "python", "file_size": 976, "cut_index": 582, "middle_length": 52 }